首页 > 代码库 > 【Lintcode】153.Combination Sum II
【Lintcode】153.Combination Sum II
题目:
Given a collection of candidate numbers (C) and a target number (T), find all unique combinations in C where the candidate numbers sums to T.
Each number in C may only be used once in the combination.
Example
Given candidate set [10,1,6,7,2,1,5]
and target 8
,
A solution set is:
[
[1,7],
[1,2,5],
[2,6],
[1,1,6]
]
题解:
主要是去重复,多个方法,之前已经介绍过。利用set
Solution 1 ()
class Solution { public: vector<vector<int> > combinationSum2(vector<int> &num, int target) { vector<vector<int> > res; vector<int> cur; sort(num.begin(), num.end()); dfs(res, cur, num, target, 0); return res; } void dfs(vector<vector<int> > &res, vector<int> &cur, vector<int> &num, int target, int pos){ if (!num.empty() && target == 0) { res.push_back(cur); return; } for (int i = pos; i < num.size(); ++i) { if(i > pos && num[i] == num[i-1]) { continue; } if (target - num[i] >= 0) { cur.push_back(num[i]); dfs(res, cur, num, target - num[i], i + 1); cur.pop_back(); } else { break; } } } };
【Lintcode】153.Combination Sum II
声明:以上内容来自用户投稿及互联网公开渠道收集整理发布,本网站不拥有所有权,未作人工编辑处理,也不承担相关法律责任,若内容有误或涉及侵权可进行投诉: 投诉/举报 工作人员会在5个工作日内联系你,一经查实,本站将立刻删除涉嫌侵权内容。