LeetCode39:Combination Sum
2015-07-06 20:58
393 查看
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]
这道题看过好几次最开始都没看出怎么做就一直留着,结果今天在做Subsets 这道题时找到了灵感,使用深度优先的方法搜索,并且用一个vector记录向量,找到合适的向量时即将它保存在结果中,并进行回溯操作。这道题相比于Subsets中使用回溯法而言更麻烦一些。以后需要注意这种解题方法,当要求解的结果是一系列向量的集合时使用dfs搜索记录路径这种方法。对于输入candidates=[1,2] ,target=3,遍历的方向如图:
runtime:28ms
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]
这道题看过好几次最开始都没看出怎么做就一直留着,结果今天在做Subsets 这道题时找到了灵感,使用深度优先的方法搜索,并且用一个vector记录向量,找到合适的向量时即将它保存在结果中,并进行回溯操作。这道题相比于Subsets中使用回溯法而言更麻烦一些。以后需要注意这种解题方法,当要求解的结果是一系列向量的集合时使用dfs搜索记录路径这种方法。对于输入candidates=[1,2] ,target=3,遍历的方向如图:
runtime:28ms
class Solution { public: vector<vector<int>> combinationSum(vector<int>& candidates, int target) { vector<vector<int>> result; vector<int> path; sort(candidates.begin(),candidates.end()); helper(candidates,0,0,target,path,result); return result; } void helper(vector<int> &nums,int pos,int base,int target,vector<int>& path,vector<vector<int>> & result) { if(base==target) { result.push_back(path); return ; } if(base>target) return ; for(int i=pos;i<nums.size();i++) { path.push_back(nums[i]); helper(nums,i,base+nums[i],target,path,result); path.pop_back(); } } };
相关文章推荐
- print语句默认每行添加一个换行符 来自2.13
- jQuery cdn使用介绍
- Java中的System.in,System.out,System.err
- Observer观察者模式
- Mysql执行Update操作时会锁住表
- 《开源框架那些事儿21》:巧借力与借巧力
- 百度 Alexand(亚历山大)简单使用教程
- favicon.ico 的作用(收藏夹的图标文件)
- android webView总是调用手机浏览器,怎么办呢?
- 二叉树的深度
- C#第六次作业 猜猜看游戏
- 红黑树的插入创建(左旋 右旋)
- C/C++中的变量和静态变量
- ip_forward参数对Linux内核转发的影响
- 推广的欧几里德算法(求最大公约数和乘法逆元)
- css filter详解
- Summary Ranges
- VC6.0行号显示
- Android与web服务器数据交互编程---3网络爬虫项目实现虚拟浏览器的jsp后台运行
- 博客首日