Combination Sum
題目:Given a set of candidate numbers (C)
and a target number (T),
find all unique combinations in C where
the candidate numbers sums to T.
A solution set is: [7]
[2, 2, 3]
The same repeated number may be chosen from C unlimited number of times.
For example, given candidate set 2,3,6,7
and
target 7
,
public class Combination_Sum {
public List<List<Integer>> combinationSum(int[] candidates, int target) {
Arrays.sort(candidates);
List<List<Integer>> results = new ArrayList<List<Integer>>();
getResult(results,new ArrayList<Integer>(),candidates,0,target);
return results;
}
private void getResult(List<List<Integer>> results,List<Integer>cur,int[]candidates,int start,int targer){
if(targer>0){
for(int i=start;i<candidates.length&&candidates[i]<=targer;i++){
cur.add(candidates[i]);
getResult(results, cur, candidates, i, targer-candidates[i]);
cur.remove(cur.size()-1);}
}else if(targer==0){
results.add(new ArrayList<Integer>(cur));
}
}
}
Combination Sum II
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 Combination_Sum_II {
public List<List<Integer>> combinationSum2(int[] candidates, int target) {
Arrays.sort(candidates);
List<List<Integer>> results = new ArrayList<List<Integer>>();
List<Integer> cur = new ArrayList<Integer>();
getResult(results,cur, candidates, 0, target);
return results;
}
private void getResult(List<List<Integer>> results, List<Integer> cur,int[]candidates,int start,int target){
if(target==0){
results.add(new ArrayList<>(cur));
return;
}
for(int i=start;i<candidates.length&&candidates[i]<=target;i++){
//過濾重複的結果!i>start這個判斷很關鍵
if(i>=1&&candidates[i]==candidates[i-1]&&i>start) continue;
cur.add(candidates[i]);
getResult(results, cur, candidates, i+1, target-candidates[i]);
cur.remove(cur.size()-1);
}
}
}
Combination Sum III
Find all possible combinations of k numbers that add up to a number n, given that only numbers from 1 to 9 can be used and each combination should be a unique set of numbers.Ensure that numbers within the set are sorted in ascending order.
Example 1:
Input: k = 3, n = 7
Output:
[[1,2,4]]
public class Combination_Sum_III {
public List<List<Integer>> combinationSum3(int k, int n) {
List<List<Integer>> results = new ArrayList<List<Integer>>();
List<Integer>cur = new ArrayList<Integer>();
getResult(results, cur, 1, n,k);
return results;
}
private void getResult(List<List<Integer>> results,List<Integer>cur,int start,int n,int k){
if(n==0&&cur.size()==k){
results.add(new ArrayList<Integer>(cur));
}else if(n>0&&cur.size()<k){
for(int i=start;i<=9;i++){
cur.add(i);
getResult(results, cur, i+1, n-i, k);
cur.remove(cur.size()-1);
}
}
}
}