Given a set of candidate numbers (candidates)(without duplicates)and a target number (target), find all unique combinations incandidates where the candidate numbers sums totarget.

Thesamerepeated number may be chosen fromcandidates unlimited number of times.

Note:

  • All numbers (includingtarget) will be positive integers.
  • The solution set must not contain duplicate combinations.
class Solution {
    public List<List<Integer>> combinationSum(int[] candidates, int target) {
        List<List<Integer>> res = new ArrayList<>();
        if(candidates == null || candidates.length == 0)
            return res;

        Arrays.sort(candidates);
        List<Integer> line = new ArrayList<>();
        helper(res, line, candidates, 0, target);

        return res;
    }

    public void helper(List<List<Integer>> res, List<Integer> line, int[] nums, int start, int target) {
        if(target == 0) {
            res.add(new ArrayList<>(line));
            return;
        }

        for(int i = start; i < nums.length; i++){
            if(nums[i] <= target) {
                line.add(nums[i]);
                helper(res, line, nums, i, target - nums[i]);
                line.remove(line.size() - 1);
            }
        }
    }
}

results matching ""

    No results matching ""