Fork me on GitHub

39. Combination Sum

39. Combination Sum

题目

 Given a set of candidate numbers (C) (without duplicates) 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.
    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]
]

解析

  • 像这种结果要求返回所有符合要求解的题十有八九都是要利用到递归,而且解题的思路都大同小异,相类似的题目有 Path Sum II 二叉树路径之和之二,Subsets II 子集合之二,Permutations 全排列,Permutations II 全排列之二,Combinations 组合项等等,如果仔细研究这些题目发现都是一个套路,都是需要另写一个递归函数,这里我们新加入三个变量,start记录当前的递归到的下标,out为一个解,res保存所有已经得到的解,每次调用新的递归函数时,此时的target要减去当前数组的的数
class Solution_39 {
public:

	void dfs(vector<vector<int>> &vecs, vector<int> &vec, int i, int target, vector<int> &candidates)
	{
		if (target==0)
		{
			vecs.push_back(vec);
			return;
		}
		if (target<0)
		{
			return;
		}
		for (int k = i; k < candidates.size(); k++)
		{
			vec.push_back(candidates[k]);
			dfs(vecs, vec, k, target - candidates[k], candidates);
			vec.pop_back();
		}
		return;
	}

	// 默认有序
	vector<vector<int> > combinationSum(vector<int> &candidates, int target) {
		vector<vector<int>> vecs;
		vector<int> vec;
		if (candidates.size()==0)
		{
			return vecs;
		}
		sort(candidates.begin(), candidates.end());
		dfs(vecs, vec, 0, target, candidates);

		return vecs;
 	}
};


题目来源

posted @ 2018-02-04 21:23  ranjiewen  阅读(180)  评论(0编辑  收藏  举报