• [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 };
  • 相关阅读:
    CAN
    snip_opencv环境配置和测试程序
    snip_进制转换代码段
    代码高亮的调试过程
    test3
    test2
    dsBlog_杂类
    js秒数转换为时分秒
    Linux 添加硬盘挂着到指定目录
    上海居住证积分续办
  • 原文地址:https://www.cnblogs.com/skycore/p/5261412.html
Copyright © 2020-2023  润新知