• 【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等其他思路。

  • 相关阅读:
    Android中开发习惯
    Activity、Window和View三者间的关系有一定的见解
    Android底层有一定的认识,研究过相关的Android源码
    安卓工程的启动过程
    OAuth2认证有一定的了解
    屏幕适配经验
    NOIP模拟赛14
    NOIP模拟赛13
    NOIP模拟赛12
    NOIP模拟赛11
  • 原文地址:https://www.cnblogs.com/huxiao-tee/p/4317139.html
Copyright © 2020-2023  润新知