leetcode 每日一题 77. 组合

回溯法

思路:

通过回溯的思维,递归调用枚举出所有可能。

代码:

class Solution:
    def combine(self, n: int, k: int) -> List[List[int]]:
        def process(begin,path):
            if len(path) == k:
                res.append(path[:])
                return
            for i in range(begin,n+1):
                path.append(i)
                process(i+1,path)
                path.pop()
        res = []
        path = []
        process(1,path)
        return res

二进制排序组合

思路:

按照二进制顺序获得全部组合。

例如: 1,2,3,4

1,2

1,3  2,3

1,4  2,4  3,4

 

代码:

class Solution:
    def combine(self, n: int, k: int) -> List[List[int]]:
        nums = list(range(1, k + 1)) + [n + 1]
        output, j = [], 0
        while j < k:
            output.append(nums[:k])
            j = 0
            while j < k and nums[j + 1] == nums[j] + 1:
                nums[j] = j + 1
                j += 1
            nums[j] += 1
        return output

 

posted @ 2020-06-13 13:41  nil_f  阅读(125)  评论(0编辑  收藏  举报