40、Combination Sum II (DFS)

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

思路:

这道题和前一道题目的不同就是不可以重复,在递归时,pos的位置加上1即可,同时要判断下一个等于上一个数的话就直接跳过了。

代码:

 var combinationSum2 = function(candidates, target) {
            var res = [];
            var path = [];
            candidates.sort(function(a, b) {
                return a - b;
            })
            helper(candidates, target, 0, 0, path, res);
            return res;

            function helper(candidates, target, pos, base, path, res) {
                if (target === base) {
                    var temp = path.concat();
                    res.push(temp);
                    return;
                } else if (base > target) {
                    return;
                } else {
                    for (var i = pos; i < candidates.length; i++) {
                        if (i > pos && candidates[i] == candidates[i - 1]) continue;
                        path.push(candidates[i]);
                        helper(candidates, target, i + 1, base + candidates[i], path, res);
                        path.pop();

                    }
                }
            }

        };

你可能感兴趣的:(40、Combination Sum II (DFS))