码迷,mamicode.com
首页 > 其他好文 > 详细

【Lintcode】135.Combination Sum

时间:2017-05-17 23:32:59      阅读:228      评论:0      收藏:0      [点我收藏+]

标签:find   重复   number   from   dfs   ons   div   repeat   color   

题目:

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.

Example

Given candidate set [2,3,6,7] and target 7, a solution set is:

[7]
[2, 2, 3]

题解:

  这个题和LeetCode不一样,这个允许重复数字产生,那么输入[2,2,3],7 结果为[2, 2, 3], [2, 2, 3], [2, 2, 3];要么对最后结果去除重复数组,要么在处理之前就对candidates数组去重复,或者利用set不重复的特点添加数组。

Solution 1 ()

class Solution {
public:
    vector<vector<int> > combinationSum(vector<int> &candidates, int target) {
        if (candidates.empty()) {
            return {{}};               
           }
           set<vector<int> > res;
           vector<int> cur;
           sort(candidates.begin(), candidates.end());
           dfs(res, cur, candidates, target, 0);
           
           return vector<vector<int> > (res.begin(), res.end());
    }
    void dfs(set<vector<int> > &res, vector<int> &cur, vector<int> candidates, int target, int pos) {
        if (!cur.empty() && target == 0) {
            res.insert(cur);
            return;
        }
        for (int i = pos; i < candidates.size(); ++i) {
            if (target - candidates[i] >= 0) {
                cur.push_back(candidates[i]);
                dfs(res, cur, candidates, target - candidates[i], i);
                cur.pop_back();
            } else {
                break;
            }
        }
    }
};

 

【Lintcode】135.Combination Sum

标签:find   重复   number   from   dfs   ons   div   repeat   color   

原文地址:http://www.cnblogs.com/Atanisi/p/6869739.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!