首页 > 代码库 > LeetCode "Combination Sum II"
LeetCode "Combination Sum II"
The only difference with version I is: one number can only be used once:
class Solution {public: vector<vector<int> > ret; struct Rec { Rec() : sum(0) {} int sum; vector<int> v; }; void go(vector<int> cands, int level, struct Rec currRec, int target) { if(currRec.sum == target) { ret.push_back(currRec.v); return; } int desire = target - currRec.sum; int last = std::numeric_limits<int>::max(); for(int i = 0; i < cands.size(); i ++) { int cand = cands[i]; if(cand <= desire && cand != last) { if(!currRec.v.empty()) { if(cand < currRec.v[currRec.v.size() - 1]) continue; } Rec newRec = currRec; newRec.sum += cand; newRec.v.push_back(cand); vector<int> newCands = cands; newCands.erase(std::find(newCands.begin(), newCands.end(), cand)); go(newCands, level + 1, newRec, target); last = cand; } } } vector<vector<int> > combinationSum2(vector<int> &candidates, int target) { if(candidates.empty()) return ret; std::sort(candidates.begin(), candidates.end()); go(candidates, 0, Rec(), target); return ret; }};
声明:以上内容来自用户投稿及互联网公开渠道收集整理发布,本网站不拥有所有权,未作人工编辑处理,也不承担相关法律责任,若内容有误或涉及侵权可进行投诉: 投诉/举报 工作人员会在5个工作日内联系你,一经查实,本站将立刻删除涉嫌侵权内容。