[LeetCode] Combination Sum 组合之和
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:
- All numbers (including
target
) will be positive integers. - The solution set must not contain duplicate combinations.
Example 1:
Input: candidates =[2,3,6,7],
target =7
,
A solution set is:
[
[7],
[2,2,3]
]
Example 2:
Input: candidates = [2,3,5],
target = 8,
A solution set is:
[
[2,2,2,2],
[2,3,3],
[3,5]
]
像这种结果要求返回所有符合要求解的题十有八九都是要利用到递归,而且解题的思路都大同小异,相类似的题目有 Path Sum II,Subsets II,Permutations,Permutations II,Combinations 等等,如果仔细研究这些题目发现都是一个套路,都是需要另写一个递归函数,这里我们新加入三个变量,start 记录当前的递归到的下标,out 为一个解,res 保存所有已经得到的解,每次调用新的递归函数时,此时的 target 要减去当前数组的的数,具体看代码如下:
解法一:
class Solution {
public:
vector<vector<int>> combinationSum(vector<int>& candidates, int target) {
vector<vector<int>> res;
vector<int> out;
combinationSumDFS(candidates, target, , out, res);
return res;
}
void combinationSumDFS(vector<int>& candidates, int target, int start, vector<int>& out, vector<vector<int>>& res) {
if (target < ) return;
if (target == ) {res.push_back(out); return;}
for (int i = start; i < candidates.size(); ++i) {
out.push_back(candidates[i]);
combinationSumDFS(candidates, target - candidates[i], i, out, res);
out.pop_back();
}
}
};
我们也可以不使用额外的函数,就在一个函数中完成递归,还是要先给数组排序,然后遍历,如果当前数字大于 target,说明肯定无法组成 target,由于排过序,之后的也无法组成 target,直接 break 掉。如果当前数字正好等于 target,则当前单个数字就是一个解,组成一个数组然后放到结果 res 中。然后将当前位置之后的数组取出来,调用递归函数,注意此时的 target 要减去当前的数字,然后遍历递归结果返回的二维数组,将当前数字加到每一个数组最前面,然后再将每个数组加入结果 res 即可,参见代码如下:
解法二:
class Solution {
public:
vector<vector<int>> combinationSum(vector<int>& candidates, int target) {
vector<vector<int>> res;
sort(candidates.begin(), candidates.end());
for (int i = ; i < candidates.size(); ++i) {
if (candidates[i] > target) break;
if (candidates[i] == target) {res.push_back({candidates[i]}); break;}
vector<int> vec = vector<int>(candidates.begin() + i, candidates.end());
vector<vector<int>> tmp = combinationSum(vec, target - candidates[i]);
for (auto a : tmp) {
a.insert(a.begin(), candidates[i]);
res.push_back(a);
}
}
return res;
}
};
我们也可以用迭代的解法来做,建立一个三维数组 dp,这里 dp[i] 表示目标数为 i+1 的所有解法集合。这里的i就从1遍历到 target 即可,对于每个i,都新建一个二维数组 cur,然后遍历 candidates 数组,如果遍历到的数字大于i,说明当前及之后的数字都无法组成i,直接 break 掉。否则如果相等,那么把当前数字自己组成一个数组,并且加到 cur 中。否则就遍历 dp[i - candidates[j] - 1] 中的所有数组,如果当前数字大于数组的首元素,则跳过,因为结果要求是要有序的。否则就将当前数字加入数组的开头,并且将数组放入 cur 之中即可,参见代码如下:
解法三:
class Solution {
public:
vector<vector<int>> combinationSum(vector<int>& candidates, int target) {
vector<vector<vector<int>>> dp;
sort(candidates.begin(), candidates.end());
for (int i = ; i <= target; ++i) {
vector<vector<int>> cur;
for (int j = ; j < candidates.size(); ++j) {
if (candidates[j] > i) break;
if (candidates[j] == i) {cur.push_back({candidates[j]}); break;}
for (auto a : dp[i - candidates[j] - ]) {
if (candidates[j] > a[]) continue;
a.insert(a.begin(), candidates[j]);
cur.push_back(a);
}
}
dp.push_back(cur);
}
return dp[target - ];
}
};
Github 同步地址:
https://github.com/grandyang/leetcode/issues/39
类似题目:
Letter Combinations of a Phone Number
参考资料:
https://leetcode.com/problems/combination-sum/
https://leetcode.com/problems/combination-sum/discuss/16825/Recursive-java-solution
https://leetcode.com/problems/combination-sum/discuss/16509/Iterative-Java-DP-solution
LeetCode All in One 题目讲解汇总(持续更新中...)
[LeetCode] Combination Sum 组合之和的更多相关文章
- [LeetCode] 39. Combination Sum 组合之和
Given a set of candidate numbers (candidates) (without duplicates) and a target number (target), fin ...
- [leetcode]39. Combination Sum组合之和
Given a set of candidate numbers (candidates) (without duplicates) and a target number (target), fin ...
- LeetCode OJ:Combination Sum (组合之和)
Given a set of candidate numbers (C) and a target number (T), find all unique combinations in C wher ...
- [LeetCode] Combination Sum IV 组合之和之四
Given an integer array with all positive numbers and no duplicates, find the number of possible comb ...
- [LeetCode] Combination Sum III 组合之和之三
Find all possible combinations of k numbers that add up to a number n, given that only numbers from ...
- [LeetCode] Combination Sum II 组合之和之二
Given a collection of candidate numbers (C) and a target number (T), find all unique combinations in ...
- LeetCode: Combination Sum 解题报告
Combination Sum Combination Sum Total Accepted: 25850 Total Submissions: 96391 My Submissions Questi ...
- [Leetcode] Combination Sum 系列
Combination Sum 系列题解 题目来源:https://leetcode.com/problems/combination-sum/description/ Description Giv ...
- LeetCode:Combination Sum I II
Combination Sum Given a set of candidate numbers (C) and a target number (T), find all unique combin ...
随机推荐
- context:component-scan" 的前缀 "context" 未绑定。
SpElUtilTest.testSpELLiteralExpressiontestSpELLiteralExpression(cn.zr.spring.spel.SpElUtilTest)org.s ...
- GitHub更新自己Fork的项目
转自:http://www.tuicool.com/articles/MzMJre github上有个功能叫fork,可以将别人的工程复制到自己账号下.这个功能很方便,但其有一个缺点是:当源项目更新后 ...
- 类型“System.Data.Linq.DataContext”在未被引用的程序集中定义。必须添加对程序集“System.Data.Linq, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089”的引用。
解决方法:添加System.Data.Linq.dll引用 http://www.cnblogs.com/m84641693/archive/2010/07/26/1785100.html http: ...
- C# 高效编程笔记2
C# 高效编程笔记2 1.理解GetHashCode()的陷阱 (1)作用:作为基于散列集合定义键的散列值,如:HashSet<T>,Dictionary<K,V>容器等 (2 ...
- C#开发微信门户及应用(23)-微信小店商品管理接口的封装和测试
在上篇<C#开发微信门户及应用(22)-微信小店的开发和使用>里面介绍了一些微信小店的基础知识,以及对应的对象模型,本篇继续微信小店的主题,介绍其中API接口的封装和测试使用.微信小店的相 ...
- 关于 .NET Core 动态链接库的开发
上个月月底,VS2017RC版发布了,一个很大的特点就是将原来的xProj文件又改回了csproj了. 这样一改,其实很多新的问题也暴露出来了,最严重的问题就是Net版本兼容性. 原来的Net体系大致 ...
- python中的TypeError错误解决办法
新手在学习python时候,会遇到很多的坑,下面来具体说说其中一个. 在使用python编写面向对象的程序时,新手可能遇到TypeError: this constructor takes no ar ...
- golang os.OpenFile
os.O_WRONLY | os.O_CREATE | O_EXCL [如果已经存在,则失败] os.O_WRONLY | os.O_CREATE ...
- 开源物联网通讯框架ServerSuperIO,成功移植到Windows10 IOT,在物联网和集成系统建设中降低成本。附:“物联网”交流大纲
[开源]C#跨平台物联网通讯框架ServerSuperIO(SSIO)介绍 一.概述 经过一个多月晚上的时间,终于把开源物联网通讯框架ServerSuperIO成功移植到Windows10 IOT上, ...
- mysql can't create threads in threadpool
最近,我们在券商端的mysql运行一段时间后,发生mysql can't create threads in threadpool,如下所示: 据官网一个报告显示,目测是一个bug,内存紧张导致,那天 ...