39 Combination Sum
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 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<int> out;
vector<vector<int>> res;
//sort(candidates.begin(), candidates.end()); 不用排序
dfs(candidates, res, out, 0, target);
return res;
}
void dfs(vector<int>& candidates, vector<vector<int>> &res, vector<int> out, int start, int target) {
if(target < 0) return; // dfs先写返回状态
else if(target == 0) res.push_back(out);
else {
for(int i = start; i < candidates.size(); ++i) {
out.push_back(candidates[i]); // 将可能存在的解存入out中
dfs(candidates, res, out, i, target - candidates[i]); // 递归调用,更新target
out.pop_back();
}
}
return; // 养成习惯,最后写返回
}
};
40 Combination Sum II
Given a collection of candidate numbers (C) and a target number (T), find all unique combinations in C where the candidate numbers sums to T.
Each number in C may only be used once in the combination.
Note:
- All numbers (including target) will be positive integers.
- The solution set must not contain duplicate combinations.
For example, given candidate set [10, 1, 2, 7, 6, 1, 5]
and target 8
,
A solution set is:
[ [1, 7], [1, 2, 5], [2, 6], [1, 1, 6] ]
</div>
这道题跟之前那道 Combination Sum 组合之和 本质没有区别,只需要改动一点点即可,之前那道题给定数组中的数字可以重复使用,而这道题不能重复使用。
先将candidates进行排序,在res.push_back()的时候检查是否存在重复。
class Solution {
public:
vector<vector<int>> combinationSum2(vector<int>& candidates, int target) {
vector<vector<int>> res;
vector<int> out;
sort(candidates.begin(), candidates.end());
dfs(candidates, res, out, 0, target);
return res;
}
void dfs(vector<int> &candidates, vector<vector<int>> &res, vector<int> &out, int start, int target) {
if(target < 0) return;
else if(target == 0 && find(res.begin(), res.end(), out) == res.end()) res.push_back(out); // 加入res前检查是否存在相同排列
else {
for(int i = start; i < candidates.size(); ++i) {
out.push_back(candidates[i]);
dfs(candidates, res, out, i+1, target - candidates[i]);
out.pop_back();
}
}
return;
}
};
或者换一种排除重复的方法:只需要在之前的基础上修改两个地方即可,首先在递归的for循环里加上if (i > start && num[i] == num[i - 1]) continue; 这样可以防止res中出现重复项,然后就在递归调用combinationSum2DFS里面的参数换成i+1,这样就不会重复使用数组中的数字了,代码如下:
class Solution {
public:
vector<vector<int> > combinationSum2(vector<int> &num, int target) {
vector<vector<int> > res;
vector<int> out;
sort(num.begin(), num.end());
combinationSum2DFS(num, target, 0, out, res);
return res;
}
void combinationSum2DFS(vector<int> &num, int target, int start, vector<int> &out, vector<vector<int> > &res) {
if (target < 0) return;
else if (target == 0) res.push_back(out);
else {
for (int i = start; i < num.size(); ++i) {
if (i > start && num[i] == num[i - 1]) continue;
out.push_back(num[i]);
combinationSum2DFS(num, target - num[i], i + 1, out, res);
out.pop_back();
}
}
}
};
216 Combination Sum III
Find all possible combinations of k numbers that add up to a number n, given that only numbers from 1 to 9 can be used and each combination should be a unique set of numbers.
Example 1:
Input: k = 3, n = 7
Output:
[[1,2,4]]
Example 2:
Input: k = 3, n = 9
Output:
[[1,2,6], [1,3,5], [2,3,4]]
Credits:
Special thanks to @mithmatt for adding this problem and creating all test cases.
这道题题是组合之和系列的第三道题,跟之前两道Combination Sum 组合之和,Combination Sum II 组合之和之二都不太一样,那两道的联系比较紧密,变化不大,而这道跟它们最显著的不同就是这道题的个数是固定的,为k。个人认为这道题跟那道Combinations 组合项更相似一些,但是那道题只是排序,对k个数字之和又没有要求。所以实际上这道题是它们的综合体,两者杂糅到一起就是这道题的解法了,n是k个数字之和,如果n小于0,则直接返回,如果n正好等于0,而且此时out中数字的个数正好为k,说明此时是一个正确解,将其存入结果res中,具体实现参见代码入下:
class Solution {
public:
vector<vector<int>> combinationSum3(int k, int n) {
vector<vector<int>> res;
vector<int> out;
dfs(res, out, 1, n, 0, k);
return res;
}
void dfs(vector<vector<int>> &res, vector<int> &out, int start, int target, int num, int tal) {
if(target < 0 || num > tal) return;
else if(target == 0 && find(res.begin(), res.end(), out) == res.end() && num == tal) res.push_back(out);
else {
for(int i = start; i <= 9; ++i) {
out.push_back(i);
dfs(res, out, i+1, target - i, num+1, tal);
out.pop_back();
}
}
return;
}
};
笔记:举一反三编程。
377 Combination Sum IV
Given an integer array with all positive numbers and no duplicates, find the number of possible combinations that add up to a positive integer target.
Example:
nums = [1, 2, 3] target = 4 The possible combination ways are: (1, 1, 1, 1) (1, 1, 2) (1, 2, 1) (1, 3) (2, 1, 1) (2, 2) (3, 1) Note that different sequences are counted as different combinations. Therefore the output is 7.
Follow up:
What if negative numbers are allowed in the given array?
How does it change the problem?
What limitation we need to add to the question to allow negative numbers?
Credits:
Special thanks to @pbrother for adding this problem and creating all test cases.
这道题是组合之和系列的第四道,我开始想当然的一位还是用递归来解,结果写出来发现TLE了,的确OJ给了一个test case为[4,1,2] 32,这个结果是39882198,用递归需要好几秒的运算时间,实在是不高效,估计这也是为啥只让返回一个总和,而不是返回所有情况,不然机子就爆了。而这道题的真正解法应该是用DP来做,解题思想有点像之前爬梯子的那道题Climbing Stairs,我们需要一个一维数组dp,其中dp[i]表示目标数为i的解的个数,然后我们从1遍历到target,对于每一个数i,遍历nums数组,如果i>=x, dp[i] += dp[i - x]。这个也很好理解,比如说对于[1,2,3] 4,这个例子,当我们在计算dp[3]的时候,3可以拆分为1+x,而x即为dp[2],3也可以拆分为2+x,此时x为dp[1],3同样可以拆为3+x,此时x为dp[0],我们把所有的情况加起来就是组成3的所有情况了,参见代码如下:
class Solution {
public:
int combinationSum4(vector<int>& nums, int target) {
vector<int> dp(target + 1);
dp[0] = 1;
for (int i = 1; i <= target; ++i) {
for (auto a : nums) {
if (i >= a) dp[i] += dp[i - a];
}
}
return dp.back();
}
};
如果target远大于nums数组的个数的话,上面的算法可以做适当的优化,先给nums数组排个序,然后从1遍历到target,对于i小于数组中的数字x时,我们直接break掉,因为后面的数更大,其余地方不变,参见代码如下:
class Solution {
public:
int combinationSum4(vector<int>& nums, int target) {
vector<int> dp(target + 1);
dp[0] = 1;
sort(nums.begin(), nums.end());
for (int i = 1; i <= target; ++i) {
for (auto a : nums) {
if (i < a) break;
dp[i] += dp[i - a];
}
}
return dp.back();
}
};
笔记:较为简单的DP求解,这一问套用前面的递归结构会超时。