40. Combination Sum II

Description

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

Each number in C 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.
For example, given candidate set [10, 1, 2, 7, 6, 1, 5] and target 8,
A solution set is:

[
[1, 7],
[1, 2, 5],
[2, 6],
[1, 1, 6]
]

Solution

DFS

只需要在Combination Sum的基础上稍作变换就好了呀。

class Solution {
    public List<List<Integer>> combinationSum2(int[] candidates, int target) {
        List<List<Integer>> combinations = new ArrayList<>();
        if (candidates == null || candidates.length < 1) return combinations;
        
        Arrays.sort(candidates);
        List<Integer> combination = new ArrayList<>();
        combinationSumRecur(candidates, 0, target, combination, combinations);
        return combinations;
    }
    
    public void combinationSumRecur(int[] candidates,
                                   int begin,
                                   int target,
                                   List<Integer> combination,
                                   List<List<Integer>> combinations) {
        // important to judge this first, because begin could be out of range
        if (target == 0) { 
            combinations.add(new ArrayList<>(combination));
            return;
        }
        
        if (begin >= candidates.length || target < 0) {
            return;
        }
        
        int count = 1;
        while (begin + count < candidates.length 
               && candidates[begin] == candidates[begin + count]) {
            ++count;
        }
        
        combinationSumRecur(candidates, begin + count, target, combination, combinations);
        
        int k = 0;
        while (k < count && candidates[begin] <= target) {
            combination.add(candidates[begin]);
            target -= candidates[begin];
            combinationSumRecur(candidates, begin + count, target, combination, combinations);
            ++k;
        }
        
        while(k-- > 0) {
            combination.remove(combination.size() - 1);
        }
    }
}
最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容