leetcode111:combination-sum

题目描述

给出一组候选数C和一个目标数T,找出候选数中加起来和等于T的所有组合。
C中的数字在组合中可以被无限次使用
注意:
  • 题目中所有的数字(包括目标数T)都是正整数
  • 你给出的组合中的数字 (a 1, a 2, … , a k) 要按非递增排序 (ie, a 1 ≤ a 2 ≤ … ≤ a k).
  • 结解集中不能包含重复的组合
 
例如:给定的候选数集是[2,3,6,7],目标数是7
解集是:
[7]
[2, 2, 3]

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 (a 1, a 2, … , a k) must be in non-descending order. (ie, a 1 ≤ a 2 ≤ … ≤ a k).
  • The solution set must not contain duplicate combinations.


For example, given candidate set2,3,6,7and target7, 
A solution set is: 
[7]
[2, 2, 3]

class Solution {
public:
    vector<vector<int> > combinationSum(vector<int> &candidates, int target) {
        vector <vector<int>>res;
        vector<int> temp;
        sort(candidates.begin(),candidates.end());
        Sum(res,temp,candidates,0,target);
        return res;
    }
    void Sum(vector <vector <int>> &res,vector<int> &temp,vector<int >&candidates,int k,int target){
        if (target==0){
            res.push_back(temp);
            return ;
        }
        if (target <0 || k>=candidates.size())
            return ;
        vector<int> t =temp;
        temp.push_back(candidates[k]);
        Sum(res,temp,candidates,k,target-candidates[k]);
        Sum(res,t,candidates,k+1,target);
        
    }
};

posted on 2020-08-01 16:59  滚雪球效应  阅读(169)  评论(0编辑  收藏  举报