Combination sum I
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.
The same repeated number may be chosen from C unlimited number of times.
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 2,3,6,7 and target 7,
A solution set is:
[7]
[2, 2, 3]
[code]
public class Solution {
public List<List<Integer>> combinationSum(int[] candidates, int target) {
List<List<Integer>> list=new ArrayList<List<Integer>>();
ArrayList<Integer> path=new ArrayList<Integer>();
if(candidates == null || candidates.length==0)return list;
Arrays.sort(candidates);
dfs(candidates, 0, target, path, list);
return list;
}
void dfs(int[]candidates, int index, int target, ArrayList<Integer> path, List<List<Integer>> list)
{
if(target==0)
{
list.add(new ArrayList<Integer>(path));
return;
}
if(index==candidates.length)return;
int sum=0;
while(sum<=target)
{
dfs(candidates, index+1, target-sum, path, list);
path.add(candidates[index]);
sum+=candidates[index];
}
for(int i=0;i<sum/candidates[index];i++)path.remove(path.size()-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]
[code]
public class Solution {
public List<List<Integer>> combinationSum2(int[] num, int target) {
List<List<Integer>> list=new ArrayList<List<Integer>>();
ArrayList<Integer> path =new ArrayList<Integer>();
if(num==null || num.length==0)return list;
Arrays.sort(num);
dfs(num, 0, target, path, list);
return list;
}
void dfs(int[]num, int index, int target, ArrayList<Integer> path, List<List<Integer>> list)
{
if(target==0)
{
list.add(new ArrayList<Integer>(path));
return;
}
if(index==num.length || num[index]>target)return;
int i=index+1;
while(i<num.length && num[i]==num[index])
{
i++;
}
int sum=0;
for(int j=0;j<=i-index;j++)
{
//if(sum>target)break;
dfs(num, i, target-sum, path, list);
path.add(num[index]);
sum+=num[index];
}
for(int j=0;j<sum/num[index];j++)
{
path.remove(path.size()-1);
}
}
}
[Thoughts]
这种有duplicate的dfs 避免重复, for:i=0->n个 num[i]