LeetCode----- 40.Combination Sum II

Given a collection of candidate numbers (C) and a target number (T), find all unique combinations in C where the candidate numbers sums to T.

Each number in C may only be used once in the combination.

Note:

  • All numbers (including target) will be positive integers.
  • The solution set must not contain duplicate combinations.

For example, given candidate set [10, 1, 2, 7, 6, 1, 5] and target 8
A solution set is: 

[
  [1, 7],
  [1, 2, 5],
  [2, 6],
  [1, 1, 6]
]

代码如下:

public class CombinationSumII {

	public static void main(String[] args) {
		int[] candidates = new int[]{10, 1, 2, 7, 6, 1, 5};
		System.out.println(combinationSum2(candidates, 8));
	}
	
    public static List<List<Integer>> combinationSum2(int[] candidates, int target) {
    	List<List<Integer>> result = new ArrayList<List<Integer>>();
    	if(candidates.length < 0) {
    		return result;
    	}
    	Arrays.sort(candidates);
    	dfs(0,candidates,target,result,new ArrayList<Integer>());
        return result;
    }

	private static void dfs(int start, int[] candidates, int target,
			List<List<Integer>> result, ArrayList<Integer> list) {
		if(target < 0) {
			return;
		}
		if(target == 0) {
			ArrayList<Integer> set = new ArrayList<Integer>(list);
			if(!result.contains(set)){
				result.add(set);
			}
			return;
		}
		for (int i = start; i < candidates.length; i++) {
			list.add(candidates[i]);
			dfs(i+1, candidates, target-candidates[i], result, list);
			list.remove(list.size()-1);
		}
	}

}





猜你喜欢

转载自blog.csdn.net/yb1020368306/article/details/79007128