LeetCode OJ:Combination Sum (组合之和)

时间:2024-01-04 21:57:32

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 (a1, a2, … , 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]

本题需要用到DFS,只不过在在有限搜索的过程中用到了剪枝,使得在优先搜索的过程中一旦遇到了对应的值那么就返回,

不再搜索余下节点。所以这题,首先将数组排序,排序之后再使用DFS加剪枝就可以达到目标。代码如下:

 class Solution {
public:
vector<vector<int>> combinationSum(vector<int>& candidates, int target) {
tmpCdd = candidates;
sort(tmpCdd.begin(), tmpCdd.end());
this->target = target;
vector<int> tmpVec;
dfs(, tmpVec);
return result;
}
private:
int target;
vector<int> tmpCdd;
vector<vector<int>> result;
private:
void dfs(int index, vector<int> & tmpVec)
{
if(index == tmpCdd.size()) return; //到达叶节点
int tmpSum = accumulate(tmpVec.begin(), tmpVec.end(), );
if(tmpSum == target){
result.push_back(tmpVec);
return;
}else if(tmpSum > target){//剪枝
return;
}else{
for(int i = index; i < tmpCdd.size(); ++i){//这里从i开始的原因是因为参数可以是重复的
tmpVec.push_back(tmpCdd[i]);
dfs(i, tmpVec);
tmpVec.pop_back();//回溯
}
}
}
};

java版本的如下所示,思想一样,方法有一点不同,这次不对tmpCdd数组中的值每次都求和,而是每递归一次之后将target的值减去一个数传入 下次递归中,代码如下:

 public class Solution {
List<List<Integer>> ret = new ArrayList<List<Integer>>();
public List<List<Integer>> combinationSum(int[] candidates, int target) {
Arrays.sort(candidates);
for(int i = 0; i < candidates.length; ++i){
ArrayList<Integer> tmpCdd = new ArrayList<Integer>();
tmpCdd.add(candidates[i]);
dfs(i, tmpCdd, candidates, target - candidates[i]);
tmpCdd.remove(tmpCdd.size() - 1);
}
return ret;
} public void dfs(int index, List<Integer> tmpCdd, int[] candidates, int target){
if(index == candidates.length)
return;
if(target < 0)
return; //直接剪枝
if(target == 0){
ret.add(new ArrayList<Integer>(tmpCdd));
return;
}else{
for(int i = index; i < candidates.length; ++i){
tmpCdd.add(candidates[i]);
dfs(i, tmpCdd, candidates, target - candidates[i]);
tmpCdd.remove(tmpCdd.size() - 1);
}
}
}
}