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();

                    }
                }
            }

        };
最后編輯于
?著作權歸作者所有,轉載或內容合作請聯系作者
平臺聲明:文章內容(如有圖片或視頻亦包括在內)由作者上傳并發布,文章內容僅代表作者本人觀點,簡書系信息發布平臺,僅提供信息存儲服務。

推薦閱讀更多精彩內容