设为首页 加入收藏

TOP

LeetCode39:Combination Sum
2015-11-21 00:58:05 来源: 作者: 【 】 浏览:1
Tags:LeetCode39: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]

这道题看过好几次最开始都没看出怎么做就一直留着,结果今天在做Subsets 这道题时找到了灵感,使用深度优先的方法搜索,并且用一个vector记录向量,找到合适的向量时即将它保存在结果中,并进行回溯操作。这道题相比于Subsets中使用回溯法而言更麻烦一些。以后需要注意这种解题方法,当要求解的结果是一系列向量的集合时使用dfs搜索记录路径这种方法。对于输入candidates=[1,2] ,target=3,遍历的方向如图:
这里写图片描述
runtime:28ms<??http://www.2cto.com/kf/ware/vc/" target="_blank" class="keylink">vcD4NCjxwcmUgY2xhc3M9"brush:java;"> class Solution { public: vector > combinationSum(vector & candidates, int target) { vector > result; vector path; sort(candidates.begin(),candidates.end()); helper(candidates,0,0,target,path,result); return result; } void helper(vector &nums,int pos,int base,int target,vector & path,vector > & result) { if(base==target) { result.push_back(path); return ; } if(base>target) return ; for(int i=pos;i

?

】【打印繁体】【投稿】【收藏】 【推荐】【举报】【评论】 【关闭】 【返回顶部
分享到: 
上一篇HDU 5073 Galaxy(贪心) 下一篇二叉树的建立与遍历(二)(c++实..

评论

帐  号: 密码: (新用户注册)
验 证 码:
表  情:
内  容: