Combination Sum
[
[7],
[2, 2, 3]
]class Solution {
public List<List<Integer>> combinationSum(int[] candidates, int target) {
List<List<Integer>> ret = new ArrayList<>();
if(candidates == null || candidates.length == 0)
return ret;
List<Integer> path = new ArrayList<Integer>();
dfs(candidates, path, ret, target, 0 );
return ret;
}
public void dfs(int[] candidates, List<Integer> path, List<List<Integer>> ret, int sum, int pos){
if(sum < 0)
return;
if(sum == 0){
if(!ret.contains(path))
ret.add(new ArrayList<Integer>(path));
return;
}
for(int i = pos; i < candidates.length; i ++){
path.add(candidates[i]);
dfs(candidates, path, ret, sum - candidates[i], i);//pos从i开始,因为可以重复。
path.remove(path.size() - 1);
}
}
}Last updated