首页 > 代码库 > [leetcode] Combination Sum
[leetcode] Combination Sum
Combination Sum
Given a set of candidate numbers (C) 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.
- Elements in a combination (a1, a2, … , ak) must be in non-descending order. (ie, a1 ≤ a2 ≤ … ≤ ak).
- 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]
思路:
回溯算法。一个一个寻找所有可行解。最初的想法是当前和加上一个数字,递归一次与目标值进行比较,如果相等,就找到了一个,如果比目标值大,退出,如果小则继续。因为结果可以有重复元素,所以每次递归都必须从当前值继续。
这样也通过了,但是想想应该有更好地剪枝方法,于是更改了一个判断条件,如果目标值与当前和之差大于即将加上的元素,就直接退出,这样少了一次递归。可是结果并没有很明显的改变。应该有更好地剪枝方法,以后再想。
题解:
class Solution {public: vector<vector<int> > res; vector<int> tmp; void foo(vector<int> &candidates, int target, int sum, int index) { if(sum==target) { res.push_back(tmp); return; } if(sum+candidates[index]>target) return; for(int i=index;i<candidates.size();i++) { tmp.push_back(candidates[i]); sum += candidates[i]; foo(candidates, target, sum, i); sum -= candidates[i]; tmp.pop_back(); } } vector<vector<int> > combinationSum(vector<int> &candidates, int target) { sort(candidates.begin(), candidates.end()); if(candidates[0]>target) return res; foo(candidates, target, 0, 0); return res; }};
后话:
从disuss中发现了有人用dp的算法做了一遍,大概看了一下没看懂,也放上来,以后和剪枝方法一起研究。
class Solution {public: vector<vector<int> > combinationSum(vector<int> &candidates, int target) { vector< vector< vector<int> > > combinations(target + 1, vector<vector<int>>()); combinations[0].push_back(vector<int>()); for (auto& score : candidates) for (int j = score; j <= target; j++) if (combinations[j - score].size() > 0) { auto tmp = combinations[j - score]; for (auto& s : tmp) s.push_back(score); combinations[j].insert(combinations[j].end(), tmp.begin(), tmp.end()); } auto ret = combinations[target]; for (int i = 0; i < ret.size(); i++) sort(ret[i].begin(), ret[i].end()); return ret; }};
[leetcode] Combination Sum
声明:以上内容来自用户投稿及互联网公开渠道收集整理发布,本网站不拥有所有权,未作人工编辑处理,也不承担相关法律责任,若内容有误或涉及侵权可进行投诉: 投诉/举报 工作人员会在5个工作日内联系你,一经查实,本站将立刻删除涉嫌侵权内容。