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. (Medium)

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]
]

 分析:

先排个序,用DFS搜索,每个数可选可不选,然后在start > end或者candidates[start] > target后就return。

恰好candidates[start] = target满足时添加到结果中。

代码:

 1 class Solution {
 2 private:
 3     vector<vector<int>>result;
 4     void dfs(int start, int end, const vector<int>& candidates, int target, vector<int>& internal) {
 5         if (start > end) {
 6             return;
 7         }
 8         if (candidates[start] == target) {
 9             internal.push_back(candidates[start]);
10             result.push_back(internal);
11             internal.pop_back();
12             return;   
13         }
14         if (candidates[start] > target) {
15             return;
16         }
17         dfs(start + 1, end, candidates, target, internal);
18         internal.push_back(candidates[start]);
19         dfs(start, end, candidates, target - candidates[start], internal);
20         internal.pop_back();
21     }
22 public:
23     vector<vector<int>> combinationSum(vector<int>& candidates, int target) {
24         sort(candidates.begin(), candidates.end());
25         int end = candidates.size() - 1;
26         vector<int> internal;
27         dfs(0, end, candidates, target, internal);
28         return result;
29     }
30 };

 

posted @ 2016-08-26 21:11  wangxiaobao1114  阅读(220)  评论(0编辑  收藏  举报