Combination Sum II哪里做错了# JobHunting - 待字闺中
c*a
1 楼
大牛快来看看
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.
Elements in a combination (a1, a2, … , ak) must be in non-descending
order. (ie, a1 ≤ a2 ≤ … ≤ ak).
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 ArrayList> combinationSum2(int[] num, int
target) {
// Start typing your Java solution below
// DO NOT write main() function
int []buff = new int[num.length];
ArrayList> res = new ArrayList
>();
if(num.length==0) return res;
Arrays.sort(num);
comb(res,buff, num, target, 0);
return res;
}
public void comb(ArrayList> res, int[]buff, int []S,
int sum, int index){
if(sum==0){
ArrayList subset = new ArrayList();
for(int i =0; i subset.add(buff[i]);
}
Collections.sort(subset);
if(!res.contains(subset))
res.add(subset);
}
else
if(sum<0 || index == S.length) return;
else{
for(int i=index;i=0;i++){
buff[index] = S[i];
comb(res,buff,S,sum-S[i], index+1);
}
}
}
}
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.
Elements in a combination (a1, a2, … , ak) must be in non-descending
order. (ie, a1 ≤ a2 ≤ … ≤ ak).
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 ArrayList
target) {
// Start typing your Java solution below
// DO NOT write main() function
int []buff = new int[num.length];
ArrayList
>();
if(num.length==0) return res;
Arrays.sort(num);
comb(res,buff, num, target, 0);
return res;
}
public void comb(ArrayList
int sum, int index){
if(sum==0){
ArrayList
for(int i =0; i
}
Collections.sort(subset);
if(!res.contains(subset))
res.add(subset);
}
else
if(sum<0 || index == S.length) return;
else{
for(int i=index;i
buff[index] = S[i];
comb(res,buff,S,sum-S[i], index+1);
}
}
}
}