首页 > 代码库 > LeetCode: Combination Sum [038]

LeetCode: Combination Sum [038]

【题目】


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 (a1a2, … , ak) must be in non-descending order. (ie, a1 ≤ a2 ≤ … ≤ 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] 



【题意】

        给定一个候选数集合candidates,和一个目标值target。从候选数集合中选出所有可能的组合,使得它们的和为target。候选集中的数可重复选择,没有次数限制。
        几点说明:
        1. 本题所有的数都是正数
        2. 组合中的数非递减排列
        3. 组合不能重复


【思路】

        1. 对候选数集排序
        2. 递归,DFS方法求解所有组合


【代码】

class Solution {
public:
    void dfs(vector<vector<int> >&result, vector<int>&candidates, int&target, vector<int>combination, int sum, int startIndex){
        //sum-组合中已有数的和
        //startIndex-选择组合中下个数的起始位(即从候选数集中的startIndex索引位上的数开始选择)
        if(sum==target)result.push_back(combination);
        else if(sum<target){
            for(int i=startIndex; i<candidates.size(); i++){
                combination.push_back(candidates[i]);
                dfs(result,candidates,target,combination,sum+candidates[i],i);
                combination.pop_back();
            }
        }
    }
    
    vector<vector<int> > combinationSum(vector<int> &candidates, int target) {
        vector<vector<int> > result;
        int size=candidates.size();
        if(size==0)return result;
        // 排序
        sort(candidates.begin(), candidates.end());
        vector<int>combination;
        dfs(result, candidates, target, combination, 0, 0);
        return result;
    }
};