您的位置:首页 > 其它

LintCode: Combination Sum II

2015-12-02 13:56 274 查看
C++

DFS

class Solution {
public:
void help(vector<int> &a, int now, int sum, int target, vector<int> &path, vector<vector<int> > &ans, bool last) {
if (sum > target) {
return ;
}
if (now >= a.size()) {
if (sum == target) {
ans.push_back(path);
}
return ;
}
if ((now == 0) || (a[now - 1] != a[now]) || last) {
path.push_back(a[now]);
help(a, now + 1, sum + a[now], target, path, ans, true);
path.pop_back();
}
help(a, now + 1, sum, target, path, ans, false);
}
/**
* @param num: Given the candidate numbers
* @param target: Given the target number
* @return: All the combinations that sum to target
*/
vector<vector<int> > combinationSum2(vector<int> &num, int target) {
// write your code here
sort(num.begin(), num.end());
vector<int> path;
vector<vector<int> > ans;
help(num, 0, 0, target, path, ans, true);
return ans;
}
};
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: