39. Combination Sum


Given asetof candidate numbers (C)(without duplicates)and a target number (T), find all unique combinations inCwhere the candidate numbers sums toT.

Thesamerepeated number may be chosen fromCunlimited 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 };

优质内容筛选与推荐>>
1、如何查看oracle用户具有的权限和角色
2、抓老鼠啊~亏了还是赚了?
3、高性能javascript
4、本周个人进步要点20160828
5、C++学习笔记


长按二维码向我转账

受苹果公司新规定影响,微信 iOS 版的赞赏功能被关闭,可通过二维码转账支持公众号。

    阅读
    好看
    已推荐到看一看
    你的朋友可以在“发现”-“看一看”看到你认为好看的文章。
    已取消,“好看”想法已同步删除
    已推荐到看一看 和朋友分享想法
    最多200字,当前共 发送

    已发送

    朋友将在看一看看到

    确定
    分享你的想法...
    取消

    分享想法到看一看

    确定
    最多200字,当前共

    发送中

    网络异常,请稍后重试

    微信扫一扫
    关注该公众号





    联系我们

    欢迎来到TinyMind。

    关于TinyMind的内容或商务合作、网站建议,举报不良信息等均可联系我们。

    TinyMind客服邮箱:support@tinymind.net.cn