[LeetCode] Combination Sum

简介: Well, a typical backtracking problem. Make sure you are clear with the following three problems: What is a partial solution and when is it finished?...

Well, a typical backtracking problem. Make sure you are clear with the following three problems:

  1. What is a partial solution and when is it finished? --- In this problem, the partial solution is a combination and it is finished once it sums to target.
  2. How to find all the partial solutions? --- In the following code, I use a for-loop to traverse all the possible elements in candidates.
  3. When to make recursive calls? --- In the following code, once an element is added to the partial solution, we call the function to generate the remaining elements recursively.

Of course, remember to recover to the previous status once a partial solution is done. In the following code, line 18 (comb.pop_back()) is for this purpose.

The following should be self-explanatory :)

 1 class Solution {
 2 public:
 3     vector<vector<int>> combinationSum(vector<int>& candidates, int target) {
 4         sort(candidates.begin(), candidates.end());
 5         vector<vector<int> > res;
 6         vector<int> comb;
 7         combination(candidates, 0, target, comb, res);
 8         return res;
 9     }
10 private:
11     void combination(vector<int>& candidates, int start, int remain, vector<int>& comb, vector<vector<int> >& res) {
12         if (!remain) {
13             res.push_back(comb);
14             return;
15         }
16         for (int i = start; i < (int)candidates.size(); i++) {
17             if (remain >= candidates[i]) {
18                 comb.push_back(candidates[i]);
19                 combination(candidates, i, remain - candidates[i], comb, res);
20                 comb.pop_back();
21             }
22         }
23     }
24 };

 

目录
相关文章
Leetcode 377. Combination Sum IV
赤裸裸的完全背包,属于动态规划的范畴,大家有兴趣可以在网上搜索下其他资料。个人觉得动态规划还是比较难理解的,更难给别人讲清楚,所以这里我直接附上我的代码供大家参考。
50 0
LeetCode 39. Combination Sum
给定一个无重复元素的数组 candidates 和一个目标数 target ,找出 candidates 中所有可以使数字和为 target 的组合。 candidates 中的数字可以无限制重复被选取。
72 0
LeetCode 39. Combination Sum
LeetCode 377. Combination Sum IV
给定一个由正整数组成且不存在重复数字的数组,找出和为给定目标正整数的组合的个数。
95 0
LeetCode 377. Combination Sum IV
LeetCode 216. Combination Sum III
找出所有相加之和为 n 的 k 个数的组合。组合中只允许含有 1 - 9 的正整数,并且每种组合中不存在重复的数字。
105 0
LeetCode 216. Combination Sum III
LeetCode 216 Combination Sum III(Backtracking)(*)
版权声明:转载请联系本人,感谢配合!本站地址:http://blog.csdn.net/nomasp https://blog.csdn.net/NoMasp/article/details/51935033 翻译 找出所有的k个数字相加得到数字n的组合,只有1到9的数字可以被使用,并且每个组合间需要是不同的数字集。
730 0
LeetCode - 39. Combination Sum
39. Combination Sum  Problem's Link  ---------------------------------------------------------------------------- Mean:  给你一个待选集合s和一个数n,让你找出集合s中相加之和为n的所有组合.
824 0
LeetCode - 40. Combination Sum II
40. Combination Sum II  Problem's Link  ---------------------------------------------------------------------------- Mean:  给你一个待选集合s和一个数n,选出所有相加之和为n的组合.
1007 0