【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,7and 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(); //撤销 } } };
相关文章推荐
- HDU 2108 字符串递归
- wget使用方法(some)
- 杭电acm 2952
- bind "xxx.js" to object using script
- 使用c++编写和使用.so动态链接库
- hdu3786 Floyd或搜索 水题
- 在Linux中用source,dot(.)和直接用脚本文件名执行shell脚本的区别
- 机器学习——深度学习(Deep Learning)
- Android支付接入(一):支付宝
- kvm简介(二)
- 分析位深度与颜色深度的关系和发展策略
- 第三周作业
- JAVA中sort()常用方法总结
- 在3D空间中绘制三角形
- 数据库mysql和mariadb的安装
- struct和union的区别
- 第6周作业-图像缩放显示
- C++中的重载丶重写丶重定义丶重定向的区别
- Linux静态库和动态库学习总结
- 高效解决 2.K-th string (微软2014在线笔试,第二题)