组合数

2017-12-15  本文已影响0人  拔丝圣代

概述


给出n和k,求 C(n, k)对应的所有组合
例如:n=4, k=2
返回:[[2,4], [3,4], [2,3], [1,2], [1,3], [1,4]]

原题


Given two integers n and k, return all possible combinations of k numbers out of 1 ... n.

For example,
If n = 4 and k = 2, a solution is:

[
  [2,4],
  [3,4],
  [2,3],
  [1,2],
  [1,3],
  [1,4],
]

思路


combine(n, k) 所有可能的组合分两部分,包含n和不包含n。其中:

例如
求combine(4, 2)

合并,得到combine(4, 2)的结果[[2,4], [3,4], [2,3], [1,2], [1,3], [1,4]]

代码


class Solution(object):
    def combine(self, n, k):
        """
        :type n: int
        :type k: int
        :rtype: List[List[int]]
        """
        if n == k:
            return [list(range(1, n+1))]
        if k == 0:
            return []
        if k == 1:
            return [[i] for i in range(1, n+1)]
        part1 = self.combine(n-1, k-1)
        part2 = self.combine(n-1, k)
        part1 = [i + [n] for i in part1]
        return part1 + part2
上一篇 下一篇

猜你喜欢

热点阅读