首页 > 代码库 > [LeetCode] 40. Combination Sum II Java

[LeetCode] 40. Combination Sum II Java

题目:

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 Solution {
    public List<List<Integer>> combinationSum2(int[] candidates, int target) {
        Arrays.sort(candidates);
        List<Integer> array= new ArrayList<>();
        List<List<Integer>> list = new ArrayList<>();
        int start=0;
        int remain=target;
        backTracking(list,array,candidates,start,remain);
        return list;
    }
	
	public void backTracking(List<List<Integer>> list,List<Integer> array,int[] candidates,int start,int remain) {
		if(remain<0)
			return;
		else if(0==remain){	//有解
			list.add(new ArrayList<>(array));
		}else{
			for(int i=start;i<candidates.length;i++){
				if(i>start&&candidates[i]==candidates[i-1]) continue;  //去重
				array.add(candidates[i]);
				backTracking(list, array, candidates, i+1, remain-candidates[i]);  //这里是i+1
				array.remove(array.size()-1);
			}
		}
		return;
	}
}

  

[LeetCode] 40. Combination Sum II Java