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

 

posted @ 2020-05-05 16:45  风不再来  阅读(114)  评论(0编辑  收藏  举报