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遍历的操作如下图所示


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

            }

        };
最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容

  • **2014真题Directions:Read the following text. Choose the be...
    又是夜半惊坐起阅读 9,890评论 0 23
  • 背景 一年多以前我在知乎上答了有关LeetCode的问题, 分享了一些自己做题目的经验。 张土汪:刷leetcod...
    土汪阅读 12,769评论 0 33
  • 和subset区别:规定了子集的sum==target 注意,这里传递的起始位置是i,而不是position+1,...
    不会停的蜗牛阅读 566评论 0 0
  • 你说走就走 南方小城 我焦急盼望 等待你的回首 你说走就走 为更美丽的风景 天边尽头 去追随久未谋面的双亲 想念...
    乔又阅读 554评论 5 5
  • 不奢求多少距离,只希望你不是漂泊者 点点滴滴都保留着,为了这一秒的过客 默默孤单,是什么,是什么 努力把难过强颜之...
    青逸人阅读 167评论 0 1