• 152. 组合


    152. 组合

    中文English

    给定两个整数 n 和 k. 返回从 1, 2, ... , n 中选出 k 个数的所有可能的组合.

    样例

    样例 1:

    输入: n = 4, k = 2
    输出: [[1,2],[1,3],[1,4],[2,3],[2,4],[3,4]]
    

    样例 2:

    输入: n = 4, k = 1
    输出: [[1],[2],[3],[4]]
    

    注意事项

    你可以以任意顺序返回所有的组合, 但是一个组合内的所有数字需要是升序排列的.

    输入测试数据 (每行一个参数)如何理解测试数据?
    class Solution:
        """
        @param n: Given the range of numbers
        @param k: Given the numbers of combinations
        @return: All the combinations of k numbers out of 1..n
        """
        def combine(self, n, k):
            # write your code here  
            d,res = [],[]
            for i in range(1,n+1):
                if i == 0:
                    d.append([i])
                else:
                    for j in range(len(d)):
                        d.append(d[j] + [i])
                    d.append([i])
    
            for z in d:
                if len(z) == k and z not in res:
                    res.append(z)
            return res
  • 相关阅读:
    预分频之三
    MySQL超时配置
    随机森林深入理解
    决策树算法——ID3
    指数平滑法
    最小二乘法的Java实现
    JS实战
    CSS布局实战
    Win7 Python开发环境搭建
    神经网络正向传播与反向传播公式
  • 原文地址:https://www.cnblogs.com/yunxintryyoubest/p/12831283.html
Copyright © 2020-2023  润新知