40. Combination Sum II (Medium)

https://leetcode.com/problems/combination-sum-ii/

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

Each number in candidates may only be used once in the combination.

Note:

  • All numbers (including target) will be positive integers.
  • The solution set must not contain duplicate combinations.

Example 1:

Input: candidates = [10,1,2,7,6,1,5], target = 8,
A solution set is:
[
  [1, 7],
  [1, 2, 5],
  [2, 6],
  [1, 1, 6]
]

Example 2:

Input: candidates = [2,5,2,1,2], target = 5,
A solution set is:
[
  [1,2,2],
  [5]
]

Solutions

ppublic class Solution {
    public List<List<Integer>> combinationSum2(int[] candidates, int target) {
        List<List<Integer>> ans = new ArrayList<>();
        if (candidates == null) {
            return ans;
        }

        Arrays.sort(candidates);

        combine(ans, new ArrayList<>(), candidates, target, 0);

        return ans;
    }

    private void combine(List<List<Integer>> ans, List<Integer> solution, int[] nums, int target, int depth) {
        if (target < 0) {
            return;
        }

        if (target == 0) {
            ans.add(new ArrayList<>(solution));

            return;
        }

        for (int i = depth; i < nums.length; i++) {
            // optimization, no need to go deeper
            if (nums[i] > target) {
                break;
            }

            // Since nums[depth] is not compared with previous one nums[depth-1].
            // For combination [1,1...] will still be included and if not add following statement
            // there will be a problem of duplicate answers.
            if (i != depth && nums[i] == nums[i - 1]) {
                continue;
            }

            solution.add(nums[i]);

            // Since every element in nums can be chosen only once
            // logic should start from i+1, not i
            combine(ans, solution, nums, target - nums[i], i + 1);

            solution.remove(solution.size() - 1);
        }
    }
}

Incorrect Solutions

References

Copyright © iovi.com 2017 all right reserved,powered by GitbookLast Modification: 2019-12-03 11:01:17

results matching ""

    No results matching ""