您的位置:首页 > 其它

[leetcode]Combination Sum

2014-06-17 19:25 399 查看


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:
//t目标数组 i当前下标 sum当前选中元素之和 vi暂存元素容器 vvi目标存储位置
void innerCS(vector<int> &t, int i, int sum, int target, vector<int> &vi, vector<vector<int> > &vvi){
int n = t.size();
if(sum > target || i == n) return; //剪支
if(sum == target) {
vvi.push_back(vi);
return;
}

for(int j = i; j < n; j++){
vi.push_back(t[j]);
innerCS(t, j, sum + t[j], target, vi, vvi);
vi.pop_back();
}
}
vector<vector<int> > combinationSum(vector<int> &candidates, int target) {
vector<vector<int> > vvi;
int n = candidates.size();
if(n == 0) return vvi;
sort(candidates.begin(), candidates.end());
vector<int> t;
for(int i = 0; i < n; i++){
if(candidates[i] > target) break;
t.push_back(candidates[i]); //一定情况下的剪支
}
vector<int> vi;
innerCS(t, 0, 0, target, vi, vvi);

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