zoukankan      html  css  js  c++  java
  • [LeetCode]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] 

    解题思路:

    回溯法,具体如下:

    对于[2, 3, 6, 7], target = 7:

    1. 第一个数字选择2,target = 7 -2 = 5;

    2. 第二个数字继续选择2(可以重复),target = 5 - 2 = 3;

    3. 第三个数字继续选择2, target = 1;

    4. 没有元素比target小,回退到第三步,target = 3;

    5. 第三个数字选择3,target = 0.

     1 class Solution {
     2 public:
     3     vector<vector<int>> combinationSum(vector<int>& candidates, int target) {
     4         sort(candidates.begin(), candidates.end());
     5         vector<vector<int>> result;
     6         vector<int> elem;
     7         combinationSum(candidates, 0, target, result, elem);
     8         return result;
     9     }
    10 private:
    11     void combinationSum(vector<int> &candidates, int index, int target, vector<vector<int>> &result, vector<int> &elem) {
    12         if (target == 0) {
    13             result.push_back(elem);
    14             return;
    15         }
    16         
    17         for (int i = index; i < candidates.size() && candidates[i] <= target; ++i) {
    18             if (i == 0 || candidates[i] != candidates[i -1]) {
    19                 elem.push_back(candidates[i]);
    20                 combinationSum(candidates, i, target - candidates[i], result, elem);
    21                 elem.pop_back();
    22             }
    23         }
    24     }
    25 };
  • 相关阅读:
    PowerToys插件扩展(类似Alfred)
    .net打独立运行环境遇到无法trim遇到的bug
    blazor wasm开发chrome插件
    将php代码部署到新浪云测试(简单方法,包含数据库的连接)
    python修改csv某一列的内容
    windows10调用libcurl
    Java动态脚本Groovy,高级啊!
    Linux 配置Git
    Java动态脚本Groovy读取配置文件
    Java动态脚本Groovy获取Bean(奇淫技巧操作)
  • 原文地址:https://www.cnblogs.com/skycore/p/5261412.html
Copyright © 2011-2022 走看看