您的位置:首页 > 其它

【LeetCode练习题】Combination Sum

2014-04-13 21:19 375 查看


Combination Sum

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]




从给定集合里找出和为Target的数的组合,一个数可以重复使用。

结果集不能重复,且每一个结果内按升序排列。

解题思路:

这是一个很好的题目,用到了回溯法,考点跟之前那道Permutation有点点像。代码有相似之处。

每次遇到下一个数时,如果它比target大,因为nums是排序的,那么肯定匹配不上了,返回。

否则的话,将这个数push_back到中间结果里,开始递归。递归结束时需要将这个数pop出来,在这个位置继续尝试下一个数。

代码如下:

class Solution {
public:
vector<vector<int> > combinationSum(vector<int> &nums, int target) {
sort(nums.begin(),nums.end());
vector<int> temp;  //中间结果
vector<vector<int>> result; //最终结果
dp(nums,0,target,temp,result);
return result;
}

void dp(vector<int> &nums,int start,int target,vector<int> &temp,vector<vector<int>> &result){
if(target == 0){   //找到了一个合法的解
result.push_back(temp);
return ;
}

for(int i = start; i < nums.size(); i++){
if(nums[i] > target){  //剪枝
return ;
}
temp.push_back(nums[i]);  //往中间向量里加一个数
dp(nums,i,target - nums[i],temp,result);
temp.pop_back();  //撤销
}
}
};
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: