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

19.2.3 [LeetCode 39] Combination Sum

时间:2019-02-03 18:11:43      阅读:150      评论:0      收藏:0      [点我收藏+]

标签:sort   without   view   ida   return   ++   ica   sed   void   

Given a set of candidate numbers (candidates) (without duplicates) and a target number (target), find all unique combinations in candidates where the candidate numbers sums to target.

The same repeated number may be chosen from candidates unlimited number of times.

Note:

  • All numbers (including target) will be positive integers.
  • The solution set must not contain duplicate combinations.

Example 1:

Input: candidates = [2,3,6,7], target = 7,
A solution set is:
[
  [7],
  [2,2,3]
]

Example 2:

Input: candidates = [2,3,5], target = 8,
A solution set is:
[
  [2,2,2,2],
  [2,3,3],
  [3,5]
]
技术图片
 1 class Solution {
 2 public:
 3     void getsum(vector<vector<int>>&res,vector<int> ans,vector<int>&candidates, int target, int lastidx) {
 4         if (target == 0) {
 5             res.push_back(ans);
 6             return;
 7         }
 8         if (target < candidates[lastidx])return;
 9         for (int i = lastidx; i < candidates.size(); i++) {
10             if (target < candidates[i])break;
11             ans.push_back(candidates[i]);
12             getsum(res, ans, candidates, target - candidates[i], i);
13             ans.pop_back();
14         }
15     }
16     vector<vector<int>> combinationSum(vector<int>& candidates, int target) {
17         sort(candidates.begin(), candidates.end());
18         vector<vector<int>>res;
19         vector<int>ans;
20         getsum(res, ans, candidates, target, 0);
21         return res;
22     }
23 };
View Code

感觉可以用dp,不知道会不会快

19.2.3 [LeetCode 39] Combination Sum

标签:sort   without   view   ida   return   ++   ica   sed   void   

原文地址:https://www.cnblogs.com/yalphait/p/10350697.html

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