zoukankan      html  css  js  c++  java
  • LeetCode39 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. (Medium)

    Note:

    • All numbers (including target) will be positive integers.
    • 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]
    ]
    

     分析:

    先排个序,用DFS搜索,每个数可选可不选,然后在start > end或者candidates[start] > target后就return。

    恰好candidates[start] = target满足时添加到结果中。

    代码:

     1 class Solution {
     2 private:
     3     vector<vector<int>>result;
     4     void dfs(int start, int end, const vector<int>& candidates, int target, vector<int>& internal) {
     5         if (start > end) {
     6             return;
     7         }
     8         if (candidates[start] == target) {
     9             internal.push_back(candidates[start]);
    10             result.push_back(internal);
    11             internal.pop_back();
    12             return;   
    13         }
    14         if (candidates[start] > target) {
    15             return;
    16         }
    17         dfs(start + 1, end, candidates, target, internal);
    18         internal.push_back(candidates[start]);
    19         dfs(start, end, candidates, target - candidates[start], internal);
    20         internal.pop_back();
    21     }
    22 public:
    23     vector<vector<int>> combinationSum(vector<int>& candidates, int target) {
    24         sort(candidates.begin(), candidates.end());
    25         int end = candidates.size() - 1;
    26         vector<int> internal;
    27         dfs(0, end, candidates, target, internal);
    28         return result;
    29     }
    30 };
  • 相关阅读:
    Java学习之路(一)——JDK的下载与安装
    无法将“add-migration”项识别为 cmdlet、函数、脚本文件或可运行程序的名称。解决方案
    VS2019只能提示选中首选项的快捷键切换
    Visual Studio空格变成点的快捷键切换
    Visual Studio 2019 打开即时窗口
    完全卸载node.js
    安装node.js和vue
    在后台启动Redis
    mysql的数据库优化方案
    hadoop
  • 原文地址:https://www.cnblogs.com/wangxiaobao/p/5811750.html
Copyright © 2011-2022 走看看