码迷,mamicode.com
首页 > 其他好文 > 详细

Leetcode dfs Combination Sum

时间:2014-09-01 12:42:03      阅读:259      评论:0      收藏:0      [点我收藏+]

标签:des   style   blog   http   color   os   io   ar   for   

Combination Sum

 Total Accepted: 17319 Total Submissions: 65259My Submissions

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


题意:给定一组数C和一个数值T,在C中找到所有总和等于T的组合。C中的同一数字可以拿多次,找到的组合不能重复。
思路:dfs
每一层的第i个节点有  n - i 个选择分支
递归深度:递归到总和大于等于T就可以返回了
复杂度:时间O(n!),空间O(n)

vector<vector<int> > res;
vector<int> _nums;
void dfs(int target, int start, vector<int> &path){
	if(target == 0) res.push_back(path);
	for(int i = start; i < _nums.size(); ++i){
		if(target < _nums[i]) return ; //这里如果没剪枝的话会超时
		path.push_back(_nums[i]);
		dfs(target - _nums[i], i, path);
		path.pop_back();
	}
}


vector<vector<int> >combinationSum(vector<int> &nums, int target){
	_nums = nums;
	sort(_nums.begin(), _nums.end());
	vector<int> path;
	dfs(target, 0, path);
	return res;
}



Leetcode dfs Combination Sum

标签:des   style   blog   http   color   os   io   ar   for   

原文地址:http://blog.csdn.net/zhengsenlie/article/details/38977093

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!