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

Each number incandidates may only be usedoncein the combination.

Note:

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

        List<Integer> line = new ArrayList<>();
        Arrays.sort(candidates);
        boolean[] visited = new boolean[candidates.length];

        helper(res, line, candidates, visited, 0, target);

        return res;
    }

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

        for(int i = start; i < nums.length; i++) {
            if(i > 0 && nums[i] == nums[i - 1] && !visited[i - 1])
                continue;

            if(nums[i] <= target) {
                line.add(nums[i]);
                visited[i] = true;
                helper(res, line, nums, visited, i + 1, target - nums[i]);
                visited[i] = false;
                line.remove(line.size() - 1);
            }
        }
    }
}

results matching ""

    No results matching ""