zoukankan      html  css  js  c++  java
  • [LeetCode] Combination Sum

    Well, a typical backtracking problem. Make sure you are clear with the following three problems:

    1. What is a partial solution and when is it finished? --- In this problem, the partial solution is a combination and it is finished once it sums to target.
    2. How to find all the partial solutions? --- In the following code, I use a for-loop to traverse all the possible elements in candidates.
    3. When to make recursive calls? --- In the following code, once an element is added to the partial solution, we call the function to generate the remaining elements recursively.

    Of course, remember to recover to the previous status once a partial solution is done. In the following code, line 18 (comb.pop_back()) is for this purpose.

    The following should be self-explanatory :)

     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> > res;
     6         vector<int> comb;
     7         combination(candidates, 0, target, comb, res);
     8         return res;
     9     }
    10 private:
    11     void combination(vector<int>& candidates, int start, int remain, vector<int>& comb, vector<vector<int> >& res) {
    12         if (!remain) {
    13             res.push_back(comb);
    14             return;
    15         }
    16         for (int i = start; i < (int)candidates.size(); i++) {
    17             if (remain >= candidates[i]) {
    18                 comb.push_back(candidates[i]);
    19                 combination(candidates, i, remain - candidates[i], comb, res);
    20                 comb.pop_back();
    21             }
    22         }
    23     }
    24 };
  • 相关阅读:
    我太难了
    树状数组模板
    题解 洛谷P1196 【[NOI2002]银河英雄传说】
    poj 2352 & Ural 1028 数星星 题解
    棋盘覆盖 题解
    2015 JSOI冬令营训练 彩色格子 题解
    题解 UVA12716 GCD等于XOR GCD XOR
    第一篇博客
    2019.8.26 小结
    2019.8.24 小结 (关于树状数组,线段树小结)
  • 原文地址:https://www.cnblogs.com/jcliBlogger/p/4584712.html
Copyright © 2011-2022 走看看