LeetCode 40.Combination Sum II

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

public class Test40 {

	public static void main(String[] args) {
		int[] candidates = {10, 1, 2, 7, 6, 1, 5};
		System.out.println(combinationSum2(candidates, 8));
	}

	public static List> combinationSum2(int[] candidates, int target) {
		Arrays.sort(candidates);
		List> result = new ArrayList<>();
		getResult(result, new ArrayList<>(), candidates, target, 0);
		return result;
    }
	
	public static void getResult(List> result, List list, int[] c, int target, int start){
		if(target > 0){
			for(int i = start; i < c.length && target >= c[i]; i++){
				list.add(c[i]);
				getResult(result, list, c, target - c[i], i + 1);
				while((i + 1 < c.length) && (c[i] == c[i + 1]))   //判断重复值
					i++;
				list.remove(list.size() - 1);
			}
		}
		else if(target == 0)
			result.add(new ArrayList<>(list));
	}
}
这个题目跟39很像,只是这个不允许重复出现,那么只需在递归调用的时候start的位置设置为 i+1即可,在后面跟判断重复值不在出现。

你可能感兴趣的:(LeetCode,LeetCode,40,Combination,Sum,II)