39. Combination Sum (DFS)

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

The same repeated number may be chosen from C unlimited number of times.

Note:
All numbers (including target) will be positive integers.
The solution set must not contain duplicate combinations.
For example, given candidate set [2, 3, 6, 7] and target 7,
A solution set is:
[
[7],
[2, 2, 3]
]

思路:

采用深度优先搜索,并用path记录向量,找到合适的就存入结果res中,并进行回溯操作
对于输入[1,2],3遍历的操作如下图所示


39. Combination Sum (DFS)_第1张图片
image.png

代码:

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

            function helper(nums, pos, base, target, path, res) {
                if (base === target) {
                    var tmp=path.concat();
                    res.push(tmp);
                    return;
                } else if (base > target) {
                    return;
                } else {
                    for (var i = pos; i < nums.length; i++) {
                        path.push(nums[i]);
                        helper(nums, i, base + nums[i], target, path, res);
                        path.pop();
                    }
                }

            }

        };

你可能感兴趣的:(39. Combination Sum (DFS))