39. Combination Sum

来源:互联网 发布:淘宝美工制作流程 编辑:程序博客网 时间:2024/06/06 01:48

题目:

Given a set of candidate numbers (C(without duplicates) 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.
  • 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]]

class Solution {public:    void combinationSum1(vector<int>& candidates,int target,int begin,vector<vector<int>> &res,vector<int>& v){        if(!target) {            res.push_back(v);            return;}        for(int i=begin;i<candidates.size()&&target>=candidates[i];i++){            v.push_back(candidates[i]);            combinationSum1(candidates,target-candidates[i],i,res,v);            v.pop_back();        }    }    vector<vector<int>> combinationSum(vector<int>& candidates, int target) {        sort(candidates.begin(),candidates.end());        vector<vector<int>> res;        vector<int> v;        combinationSum1(candidates,target,0,res,v);        return res;    }};


遇见类似于求子集,或者选择与不选择

注意push_back与pop_back的灵活使用