leetcode 40 Combination Sum II --- java

时间:2021-09-15 05:02:51

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]
]

这道题就是39题的变化版本,这里每一个数字只许出现一次,并且最后的结果不允许重复,第一次只是将上一题的代码修改了边界条件,但结果不是很理想。

public class combinationSum2 {
public List<List<Integer>> combinationSum2(int[] candidates, int target) {
List<List<Integer>> result = new ArrayList<List<Integer>>();
Arrays.sort(candidates);
getResult(candidates,target,0,result,new ArrayList<Integer>());
return result;
} public void getResult( int[] candidates, int target,int pos, List<List<Integer>> result,List<Integer> ans){
for( int i = pos;i <candidates.length; i++){
if( target == candidates[i]){
ans.add(candidates[i]);
result.add(new ArrayList<Integer>(ans));
ans.remove(ans.size()-1);
return;
}
else if(target > candidates[i]){ ans.add(candidates[i]);
getResult(candidates,target-candidates[i],i+1,result,ans);
ans.remove(ans.size()-1);
}else
return ;
}
}
/*
* 1.这道题和conbinationSum很相似,只不过不能使用重复的数字。
* 2.35+9
*/
}

之后发现,如果在getResult中,用数组代替List<Integer>那么会快很多,修改之后,做到了最快。

public class Solution {
public List<List<Integer>> combinationSum2(int[] candidates, int target) {
List<List<Integer>> result = new ArrayList<List<Integer>>();
Arrays.sort(candidates);
getResult(candidates,target,0,result,new int[candidates.length],0);
return result;
} public void getResult( int[] candidates, int target,int pos, List<List<Integer>> result,int[] ans,int num){
for( int i = pos;i <candidates.length; i++){
if( target == candidates[i]){
List<Integer> aa = new ArrayList<Integer>();
for( int ii =0; ii<num; ii++)
aa.add(ans[ii]);
aa.add(candidates[i]);
result.add(aa);
return;
}
else if(target > candidates[i]){
ans[num] = candidates[i];
getResult(candidates,target-candidates[i],i+1,result,ans,num+1);
while( i+1< candidates.length && candidates[i] == candidates[i+1])
i++; }else
return ;
}
}
}