Programming

Leetcode-40. Combination Sum II

Leetcode-40. 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 sum to target.

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

Note: The solution set must not contain duplicate combinations.

Example 1:

Input: candidates = [10,1,2,7,6,1,5], target = 8 Output: [ [1,1,6], [1,2,5], [1,7], [2,6] ] Example 2:

Input: candidates = [2,5,2,1,2], target = 5 Output: [ [1,2,2], [5] ]

<解題>

  1. 本層不能用同樣的數字 : (1)排序 (2) if(i!=start && i==start[i]) continue

class Solution {
    public List<List<Integer>> combinationSum2(int[] candidates, int target) {
        if(candidates == null ) return new ArrayList<>();
        List<List<Integer>> res = new ArrayList<>();
        Arrays.sort(candidates);
        helper(res, candidates, new ArrayList<>(), target, 0);
        return res;
    }

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

        for(int i = start; i < nums.length; i++){
            //和前一個數字ㄧ樣的話就跳掉(從第二個開始看)
            if(i != start && nums[i] == nums[i - 1]) continue;
            temp.add(nums[i]);
            helper(res, nums, temp, target - nums[i], i + 1);
            temp.remove(temp.size() - 1);
        }
    }
}

Time: O(2^n) Space: O(2^n + n)