[LeetCode 题解] Combination Sum

前言

 

【LeetCode 题解】系列传送门:  http://www.cnblogs.com/double-win/category/573499.html

 

1.题目描述

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]

2. 题意

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

输出所有唯一的组合。

3. 思路

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

采用DFS思想即可。

4: 解法

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;
    }
};

 

作者:Double_Win

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

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

posted @ 2014-08-08 17:59  Double_win  阅读(249)  评论(0编辑  收藏  举报