您当前的位置: 首页 >  Python

Better Bench

暂无认证

  • 2浏览

    0关注

    695博文

    0收益

  • 0浏览

    0点赞

    0打赏

    0留言

私信
关注
热门博文

【Leetcode刷题Python】77. 组合

Better Bench 发布时间:2022-08-02 17:35:00 ,浏览量:2

1 题目

给定两个整数 n 和 k,返回范围 [1, n] 中所有可能的 k 个数的组合。

你可以按 任何顺序 返回答案。

示例 1:

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

示例 2:

输入:n = 1, k = 1 输出:[[1]]

2 解析

(1)方法一 采用Python内置的 排列组合方法 from itertools import combinations

(2)方法二 递归: #在 [1, n] 中选 k 个数,那么按照字典序可以在 [1, n - k +1]中依次选一个数x ,然后在 [x + 1, n] 中选出 (k - 1) 个数,通过递归进行搜索即可。

3 Python实现

(1)方法一

class Solution:
    def combine(self, n: int, k: int) -> List[List[int]]:
        from itertools import combinations
        return [list(i) for i in combinations(iterable=range(1,n+1),r=k)]

(2)方法二

class Solution:
    def combine(self, n: int, k: int) -> List[List[int]]:
        # 在 [1, n] 中选 k 个数
        # 那么按照字典序可以在 [1, n - k +1]中选一个数x 
        # 然后在 [x + 1, n] 中选出 (k - 1) 个数,通过递归进行搜索即可。
        
        def merge(array,k):
            if k==1:
                return [[i] for i in array]
            else:
                ans = []
                for i in range(len(array)-k+1):
                    last = merge(array[i+1:],k-1)
                    for j in last:
                        ans.append([array[i]]+j)
                return ans
        return merge(list(range(1, n+1)), k)
关注
打赏
1665674626
查看更多评论
立即登录/注册

微信扫码登录

0.0416s