0
点赞
收藏
分享

微信扫一扫

[leetcode] 39. Combination Sum


Description

Given a set of candidate numbers (candidates) (without duplicates) and a target number (target), find all unique combinations in candidates where the candidate numbers sums to target.

The same repeated number may be chosen from candidates unlimited number of times.

Note:

  • All numbers (including target) will be positive integers.
  • The solution set must not contain duplicate combinations.
    Example 1:

Input: candidates = [2,3,6,7], target = 7,
A solution set is:
[
[7],
[2,2,3]
]

Example 2:

Input: candidates = [2,3,5], target = 8,
A solution set is:
[
[2,2,2,2],
[2,3,3],
[3,5]
]

分析

题目的意思是:给你一些候选的数,然后给出所有可能的组合数。

  • 这是一个DFS经典题目,这是一个经典的解法,递归,注意终止条件就行了。

代码

class Solution {
public:
vector<vector<int>> combinationSum(vector<int>& candidates, int target) {
vector<vector<int>> result;
vector<int> ans;
getSum(candidates,target,0,0,result,ans);
return result;
}

void getSum(vector<int>& candidates, int target,int sum,int index,vector<vector<int>> &result,vector<int> ans){
if(sum>target){
return;
}
if(sum==target){
result.push_back(ans);
}
for(int i=index;i<candidates.size();i++){
ans.push_back(candidates[i]);
getSum(candidates,target,sum+candidates[i],i,result,ans);
ans.pop_back();
}
}
};

参考文献

​​[编程题]combination-sum​​


举报

相关推荐

0 条评论