c*****a 发帖数: 808 | 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);
}
}
}
} | l*****a 发帖数: 14598 | 2 if there are duplicate in the input, you need to use
for(int i=start;i<**.length;i++) {
if(i!=start && **[i]==**[i-1]) continue;
....
}
【在 c*****a 的大作中提到】 : 大牛快来看看 : 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.
| c*****a 发帖数: 808 | 3 [3,5,7], target 10
output [[3,7],[5,5]]
expected [[3,7]]
不知道为什么5会出现两次 |
|