zoukankan      html  css  js  c++  java
  • 【leetcode】Combination Sum III(middle)

    Find all possible combinations of k numbers that add up to a number n, given that only numbers from 1 to 9 can be used and each combination should be a unique set of numbers.

    Ensure that numbers within the set are sorted in ascending order.


    Example 1:

    Input: k = 3, n = 7

    Output:

    [[1,2,4]]

    Example 2:

    Input: k = 3, n = 9

    Output:

    [[1,2,6], [1,3,5], [2,3,4]]

    思路:

    组合问题,递归,1-9 每个数字都分放入和不放入两种情况。得到满足条件的就压入答案。

    class Solution {
    public:
        vector<vector<int>> combinationSum3(int k, int n) {
            vector<int> partans;
            vector<vector<int>> ans;
            combination(1, k, n, partans, ans);
            return ans;
        }
    
        void combination(int curNum, int k, int sum, vector<int> &partans, vector<vector<int>> &ans)
        {
            if(curNum > 10 || sum < 0 || k < 0) return; //注意这里是 > 10, 否则数字9的答案无法压入
            if(sum == 0 && k == 0)
            {
                ans.push_back(partans);
            }
            else
            {
                partans.push_back(curNum);
                combination(curNum + 1, k - 1, sum - curNum, partans, ans);
                partans.pop_back();
                combination(curNum + 1, k, sum, partans, ans);
            }
        }
    };
  • 相关阅读:
    LC 155 Min Stack
    TUM 慕尼黑工业大学 MSEI 课程结构介绍 ws19/20
    C++ MinGW 配合 Sublime Text 搭建
    LC 752 Open the Lock
    LC 200 Number of Islands
    Python lambda
    关于无法连接网络安装VisualVM解决方案
    二叉堆的解读
    哈希表的实现
    红黑树解读
  • 原文地址:https://www.cnblogs.com/dplearning/p/4528598.html
Copyright © 2011-2022 走看看