您的位置:首页 > 其它

[leetcode] Combination Sum

2014-12-27 13:11 302 查看

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> > 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;
}
};


View Code
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: