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.

For example, given candidate set [2, 3, 6, 7] and target 7, 
A solution set is: 
[
  [7],
  [2, 2, 3]
]

给一个数组C和一个目标值T,求C中数字的各种组合,使其和等于目标T,每个元素可以使用无限次。

用回溯法穷举就可以了,不过要限定只能向后选数字,不然会造成重复。具体在算法实现中,添加一个当前判定数字位置的pos变量就可以了。

 1 class Solution {
 2 public:
 3     void helper(vector<int>& candidates, int target, int sum, int pos, vector<int> v, vector<vector<int>>& res) {
 4         if (sum==target) {
 5             res.push_back(v);
 6             return;
 7         }
 8         for (int i=pos; i<candidates.size(); ++i) {
 9             if (sum+candidates[i]<=target) {
10                 v.push_back(candidates[i]);
11                 sum += candidates[i];
12                 helper(candidates, target, sum, i, v, res);
13                 sum -= candidates[i];
14                 v.pop_back();
15             }
16         }
17     }
18     vector<vector<int>> combinationSum(vector<int>& candidates, int target) {
19         vector<vector<int>> res;
20         vector<int> v;
21         helper(candidates, target, 0, 0, v, res);
22         return res;
23     }
24 };

 

posted @ 2017-12-20 20:58  Zzz...y  阅读(146)  评论(0编辑  收藏  举报