zoukankan      html  css  js  c++  java
  • 【Leetcode】【Medium】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 (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]  

    解题思路:

    使用回溯的思想穷举可能的结果。

    代码:

     1 class Solution {
     2 public:
     3     vector<vector<int>> combinationSum(vector<int>& candidates, int target) {
     4         vector<vector<int>> lst;
     5         vector<int> ans;
     6         sort(candidates.begin(), candidates.end());
     7         Backtracking(lst, ans, candidates, 0, target);
     8         return lst;
     9     }
    10     
    11     void Backtracking(vector<vector<int>> &lst, vector<int> ans, vector<int> candidates, int idx, int left) {
    12         for (int i = idx; i < candidates.size(); ++i) {
    13             int cur_left = left - candidates[i];
    14             if (cur_left == 0) {
    15                 ans.push_back(candidates[i]);
    16                 lst.push_back(ans);
    17                 return;
    18             }
    19             if (cur_left > 0) {
    20                 ans.push_back(candidates[i]);
    21                 Backtracking(lst, ans, candidates, i, cur_left);
    22                 ans.pop_back();
    23             } else {
    24                 return;
    25             } 
    26         }
    27     }
    28 };

    另:是否还有DP/DFS等其他思路。

  • 相关阅读:
    添加可运行的js代码
    一,IL访问静态属性和字段
    UI基础UIWindow、UIView
    ASP.NET MVC:会导致锁定的会话
    2013腾讯编程马拉松初赛
    使用phantomjs生成网站快照
    C语言
    设置 Ext.data.Store 传参的请求方式
    HDU 2041 超级楼梯
    MySQL 监控-innotop
  • 原文地址:https://www.cnblogs.com/huxiao-tee/p/4317139.html
Copyright © 2011-2022 走看看