# 39. Combination Sum

class Solution {
public:
void Getans(vector<int>& nums,int sta,vector<vector<int>>& res,int cur,vector<int> ans,int target)
{
if(cur==target&&ans.size()>0)
{
res.push_back(ans);
return;
}
if(nums[sta]>target||nums[sta]+cur>target||sta>=nums.size())
return;

Getans(nums,sta+1,res,cur,ans,target);
ans.push_back(nums[sta]);
Getans(nums,sta,res,cur+nums[sta],ans,target);
}
vector<vector<int>> combinationSum(vector<int>& candidates, int target) {
int n=candidates.size();
sort(candidates.begin(),candidates.end());
vector<vector<int>> res;
vector<int> ans;
Getans(candidates,0,res,0,ans,target);
return res;
}
};

update:

class Solution {
public:
void Getans(vector<int>& nums,int sta,vector<vector<int>>& res,int cur,vector<int> ans,int target)
{
if(cur==target&&ans.size()>0)
{
res.push_back(ans);
return;
}
if(cur>target)
return;
for(int i=sta;i<nums.size();i++)
{
ans.push_back(nums[i]);
Getans(nums,i,res,cur+nums[i],ans,target);
ans.pop_back();
}
}
vector<vector<int>> combinationSum(vector<int>& candidates, int target) {
int n=candidates.size();
sort(candidates.begin(),candidates.end());
vector<vector<int>> res;
vector<int> ans;
Getans(candidates,0,res,0,ans,target);
return res;
}
};

• 本文已收录于以下专栏：

## leetcode【39+40+216+377 Combination Sum 相关】【python】

39Combination Sum是说让我们在给定数组C中找到所有的组合，使得组合中数字的和是target值。并且组合里的数字可以重复，也就是不限制C中每一个数字的使用。 这明显是回溯啦，大家记得让...

## 39. Combination Sum [leetcode][javascript解法]

Combination Sum Add to List QuestionEditorial Solution My Submissions Total Accepted: 128797 To...
• dayuqi
• 2016年12月13日 23:00
• 150

## [leetcode] 39& 40 Combination Sum I& II

if (i != index && num[i] == num[i - 1]) continue; Given a set of candidate numbers (C) and a target...

## leetcode - 39. Combination Sum

39. Combination Sum Given a set ofcandidate numbers (C) (without duplicates) and atarget number (T)...
• laeen
• 2017年02月27日 11:10
• 200

## leetcode 39. Combination Sum

Given a set of candidate numbers (C) and a target number (T), find all unique combinations in C wher...

举报原因： 您举报文章：39. Combination Sum 色情 政治 抄袭 广告 招聘 骂人 其他 (最多只允许输入30个字)