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

[LeetCode: 题解] Combination Sum

时间:2014-08-08 20:54:46      阅读:246      评论:0      收藏:0      [点我收藏+]

标签:des   style   blog   http   color   os   io   strong   

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, a1a2 ≤ … ≤ 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]

题意:

给定一个候选集合,集合中的元素以非递减方式存放。给定一个目标值T

输出所有唯一的组合。

思路:

由于不能出现重复元组,所以我们先将candidate set进行排序,然后规定比新插入的元素不能比当前元素小。

采用DFS思想即可。

解法如下:

 

class Solution {
private:
    vector<int> ans;
    vector<vector<int> > ret;
public:
    void DFS(int start,vector<int> &candidates, int target){
        if(target==0){
            ret.push_back(ans);
            return;
        }

        for(int i=start;i<candidates.size();++i){
            if(target <candidates[i]) return;
            ans.push_back(candidates[i]);
            DFS(i,candidates,target-candidates[i]);
            ans.pop_back();
        }
    }
    vector<vector<int> > combinationSum(vector<int> &candidates, int target) {
        ans.clear();
        ret.clear();
        if(!target || !candidates.size()) return ret;
        sort(candidates.begin(),candidates.end());
        DFS(0,candidates,target);
        return ret;
    }
};

 

-------------------------------------------------

bubuko.com,布布扣

作者:Double_Win

出处: http://www.cnblogs.com/double-win/p/3896010.html 

声明: 由于本人水平有限,文章在表述和代码方面如有不妥之处,欢迎批评指正~

[LeetCode: 题解] Combination Sum,布布扣,bubuko.com

[LeetCode: 题解] Combination Sum

标签:des   style   blog   http   color   os   io   strong   

原文地址:http://www.cnblogs.com/double-win/p/3899927.html

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