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]
]

Hints

Solutions

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

        Arrays.sort(candidates);
        combine(rst, new ArrayList<Integer>(), candidates, target, 0);

        return rst;
    }

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

        if (target == 0) {
            rst.add(new ArrayList<>(solution));
            return;
        }

        for (int i = depth; i < nums.length; i++) {
            if (nums[i] > target) {
                break;
            }

            // since the nums are sorted, the following if case will be redundant
            if (i > depth && nums[depth] == nums[i]) {
                continue;
            }

            // nums[i-1] has already swapped
            // swap(nums, depth, i) makes no difference
            if (i > depth && nums[i] == nums[i - 1]) {
                continue;
            }

            solution.add(nums[i]);
            combine(rst, solution, nums, target - nums[i], i+1);
            solution.remove(solution.size() - 1);
        }
    }
}
Copyright © iovi.com 2017 all right reserved,powered by GitbookLast Modification: 2019-04-21 20:45:06

results matching ""

    No results matching ""