zoukankan      html  css  js  c++  java
  • Leetcode题解(4):L216/Combination Sum III

    L216: Combination Sum III
      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]]

    解题思路:递归,注意一些条件的处理,避免不必要的处理

    class Solution {
    public:
    bool combine(int min, int k, int n, vector<int> vec, vector<vector<int>>& result){
            if(n<min*k)         //更确切的。能够用等差数列公式算出最大值最小值
                return false;
            if(n>9*k)
                return true;
    
            if(k==1)
            {
                vec.push_back(n);
                result.push_back(vec);
                return true;
            }
    
            for(int i=min;i<=9;i++)
            {
                vec.push_back(i);
                bool rt = combine(i+1, k-1,n-i, vec, result);
                vec.pop_back();
                if(!rt)
                    break;
            }
            return true;
        }
    
        vector<vector<int>> combinationSum3(int k, int n) {
            vector<vector<int>> result;
            vector<int> vec;
            combine(1,k,n,vec,result);
            return result;
        }
    };
  • 相关阅读:
    linux gcc安装
    重装win7后如何恢复ubuntu引导
    Eclipse搭建Android开发环境(安装ADT,Android4.4.2)
    mysql变量使用总结
    最快得到MYSQL两个表的差集
    mysqldb
    更改时间 (时分秒)
    使用命令转移文件
    报喜啦~过了!
    Jmeter接口测试示例
  • 原文地址:https://www.cnblogs.com/claireyuancy/p/7191451.html
Copyright © 2011-2022 走看看