• 216. Combination Sum III


    题目:

    从1~9个数中,取k个数,使其和为n,求所有的组合

    例子:

    Input: k = 3, n = 9
    Output: [[1,2,6], [1,3,5], [2,3,4]]

    方法:

    keyword:栈,递归

    1. 对于1~9的每一个数,

    用掉一个,则在剩下的数里面寻找满足的数。

    2.结束条件:

    k只剩下一个数,且剩下的数的最小值<n,最大值>n

    3.结果保存:

    每一次得到的临时结果:每一个数组,+当前的这个数

    再把这个结果,push到最终结果

    参考代码:

     1 class Solution {
     2 public:
     3     void helper(vector<vector<int>>& res, int k, int n, int start){
     4         if(n<=0||k<=0||start>9) return;
     5         if(k==1){
     6             if(n<=9 && n>=start){
     7                 res.push_back({n});
     8             }
     9             return;
    10         }
    11         
    12         for(int i=start; i<=9; i++){
    13             vector<vector<int>> tmpres;
    14             helper(tmpres, k-1, n-i, i+1);
    15             for(vector<int> k:tmpres){
    16                 k.push_back(i);
    17                 res.push_back(k);
    18             }
    19         }
    20     }
    21     vector<vector<int>> combinationSum3(int k, int n) {
    22         vector<vector<int>> res;
    23         helper(res, k, n, 1);
    24         return res;
    25     }
    26 };
  • 相关阅读:
    3.27上午
    3.24上午 补
    2017.3.27下午
    2017.3.27上午
    2017.3.24下午
    2017.3.24上午
    2017.3.23下午
    2017.3.23上午
    2017.3.22上午
    2017.3.21下午
  • 原文地址:https://www.cnblogs.com/habibah-chang/p/12390409.html
Copyright © 2020-2023  润新知