小旭讲解 LeetCode 39. Combination Sum 回溯法

栏目: 编程工具 · 发布时间: 6年前

内容简介:Given aThe回溯法(深度优先搜索,Depth-First Search)

原题

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

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

Note:

target

Example 1:

<strong>Input:</strong> candidates = <code>[2,3,6,7], </code>target = <code>7</code>,
<strong>A solution set is:</strong>
[
  [7],
  [2,2,3]
]

Example 2:

<strong>Input:</strong> candidates = [2,3,5]<code>, </code>target = 8,
<strong>A solution set is:</strong>
[
  [2,2,2,2],
  [2,3,3],
  [3,5]
]

题解

讲义

考察知识点:

回溯法(深度优先搜索,Depth-First Search)

回溯法搜索轨迹示意图:

小旭讲解 LeetCode 39. Combination Sum 回溯法

代码

class Solution {
public:
    vector<vector <int>> combinationSum(vector<int>& candidates, int target) {
        vector<vector <int>> result{};
        vector<int> candidate{};
        sort(candidates.begin(), candidates.end());
        sum(result, candidates, target, candidate, 0);
        return result;
    }
    
    void sum(vector<vector <int>>& result, vector<int>& candidates, int target, vector</int><int>& candidate, int level) {
        // up to the target
        if (target == 0) {
            result.push_back(candidate);
            return;
        }
        for (int i = level; i < candidates.size() && candidates[i] <= target; ++i) {
            candidate.push_back(candidates[i]);
            sum(result, candidates, target - candidates[i], candidate, i);
            candidate.pop_back();
        }
    }
};

文章来源:胡小旭 => 小旭讲解 LeetCode 39. Combination Sum 回溯法

题解视频背景音乐:《Sad Angel》

延伸阅读: zh.wikipedia.org/wiki/回溯法


以上所述就是小编给大家介绍的《小旭讲解 LeetCode 39. Combination Sum 回溯法》,希望对大家有所帮助,如果大家有任何疑问请给我留言,小编会及时回复大家的。在此也非常感谢大家对 码农网 的支持!

查看所有标签

猜你喜欢:

本站部分资源来源于网络,本站转载出于传递更多信息之目的,版权归原作者或者来源机构所有,如转载稿涉及版权问题,请联系我们

另一个地球

另一个地球

[美]马克·格雷厄姆、威廉·H·达顿 / 胡泳、徐嫩羽 / 电子工业出版社 / 2015-10-1 / 78

互联网在日常工作和生活中扮演日益重要的角色,互联网将如何重塑社会?本书通过汇集有关互联网文化、经济、政治角色等问题的研究成果,提供了特定社会制度背景下解决这一问题的根本办法。 关于互联网的研究是蓬勃发展的崭新领域,牛津大学互联网研究院(OII)作为创新型的跨学科学院,自成立起就专注于互联网研究。牛津大学互联网研究院关于互联网+社会的系列讲座在一定程度上塑造了互联网+社会。本书内容基于不同学科......一起来看看 《另一个地球》 这本书的介绍吧!

HTML 压缩/解压工具
HTML 压缩/解压工具

在线压缩/解压 HTML 代码

Base64 编码/解码
Base64 编码/解码

Base64 编码/解码

HSV CMYK 转换工具
HSV CMYK 转换工具

HSV CMYK互换工具