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

Combination Sum - LeetCode

时间:2015-11-10 15:47:45      阅读:161      评论:0      收藏:0      [点我收藏+]

标签:

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

思路:我们通过backtracking来记录所有的值。这道题里用一个函数assist来协助完成。

对于这一串数,我们先将其排序,然后枚举每一个小于当前target的位置。假如现在枚举到了第i个数,则递归寻找从第i位开始所有累加和为target - candidates[i]的可能。

 1 public:
 2     void assist(vector<int>& candidates, vector<vector<int> >& res, vector<int>& cur, int target, int st)
 3     {
 4         if (target == 0)
 5         {
 6             res.push_back(cur);
 7             return;
 8         }
 9         for (int i = st, n = candidates.size(); i < n && candidates[i] <= target; i++)
10         {
11             cur.push_back(candidates[i]);
12             assist(candidates, res, cur, target - candidates[i], i);
13             cur.pop_back();
14         }
15     }
16     vector<vector<int>> combinationSum(vector<int>& candidates, int target) {
17         vector<vector<int> > res;
18         vector<int> cur;
19         sort(candidates.begin(), candidates.end(), less<int>());
20         assist(candidates, res, cur, target, 0);
21         return res;
22     }
23 };

 

Combination Sum - LeetCode

标签:

原文地址:http://www.cnblogs.com/fenshen371/p/4952850.html

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