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$.

The same repeated number may be chosen from $C$ unlimited number of times.

Note:

All numbers (including target) will be positive integers.
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]
]

Solution:

public class Solution {
    public List<List<Integer>> combinationSum(int[] candidates, int target) {
        Arrays.sort(candidates);
        List<List<Integer>> ans = new ArrayList<>();
        combinationSum(ans, candidates, target, 0, new ArrayList<Integer>());
        return ans;
    }
    public void combinationSum(List<List<Integer>> ans, int[] candidates, int target, int start, List<Integer> list){
        if(target==0){
            ans.add(new ArrayList<>(list));
            return;
        }
        for(int i=start; i<candidates.length; i++){
            if(target-candidates[i]<0) break;
            list.add(candidates[i]);
            combinationSum(ans, candidates, target-candidates[i], i, list);
            list.remove(list.size()-1);
        }
    }
}
comments powered by Disqus