[LeetCode] 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 (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] 

一开始想到用背包DP做,用DP的好处是速度快。但打印结果比较麻烦。DP比较适合打印总共有几种情况。所以就用DFS来做。

 1 class Solution {
 2 private:
 3     vector<vector<int> > ret;
 4     vector<int> a;
 5 public:
 6     void solve(int dep, int maxDep, int target, vector<int> &cand)
 7     {
 8         if (target < 0)
 9             return;
10             
11         if (dep == maxDep)
12         {
13             if (target == 0)
14             {
15                 vector<int> res;
16                 for(int i = 0; i < maxDep; i++)
17                     for(int j = 0; j < a[i]; j++)
18                         res.push_back(cand[i]);
19                 ret.push_back(res);
20             }
21             return;
22         }
23         
24         for(int i = 0; i <= target / cand[dep]; i++)
25         {
26             a[dep] = i;
27             solve(dep + 1, maxDep, target - cand[dep] * i, cand);
28         }
29     }
30     
31     vector<vector<int> > combinationSum(vector<int> &candidates, int target) {
32         // Start typing your C/C++ solution below
33         // DO NOT write int main() function
34         sort(candidates.begin(), candidates.end());
35         
36         a.resize(candidates.size());
37         ret.clear();
38         if (candidates.size() == 0)
39             return ret;
40             
41         solve(0, candidates.size(), target, candidates);
42         
43         return ret;
44     }
45 };
posted @ 2012-10-29 17:20  chkkch  阅读(4179)  评论(0编辑  收藏  举报