美文网首页
python实现leetcode之77. 组合

python实现leetcode之77. 组合

作者: 深圳都这么冷 | 来源:发表于2021-09-12 00:13 被阅读0次

解题思路

分两种情况
1.从前面n-1个元素里取k个,一共有first_half种组合
2.从前面n-1个元素里取k-1个,再在每种方案上加上最后一个元素last,一共有second_half种组合
两种组合一起就是结果

77. 组合

代码

class Solution:
    def combine(self, n: int, k: int):
        if k > n: return []
        return combine(list(range(1, n+1)), k)


def combine(li, k):
    if k > len(li): return []
    if k == 1: return [[i] for i in li]
    *rest, last = li
    # 不包含最后一个: 从前面取k个
    first_half = combine(rest, k)
    # 包含最后一个: 从前面取k-1个,然后在追加最后一个
    second_half = [[*arr, last] for arr in combine(rest, k-1)]
    return [*first_half, *second_half]
效果图

相关文章

  • python实现leetcode之77. 组合

    解题思路 分两种情况1.从前面n-1个元素里取k个,一共有first_half种组合2.从前面n-1个元素里取k-...

  • LeetCode | 0077. Combinations组合【

    LeetCode 0077. Combinations组合【Medium】【Python】【回溯】 Problem...

  • LeetCode 力扣 77. 组合

    题目描述(中等难度) 给定 n ,k ,表示从 { 1, 2, 3 ... n } 中选 k 个数,输出所有可能,...

  • LeetCode #77 #39 #40 #216 #377 #

    77. Combinations https://leetcode.com/problems/combinatio...

  • LeetCode | 0039. Combination Sum

    LeetCode 0039. Combination Sum组合总和【Medium】【Python】【回溯】 Pr...

  • 排列组合

    python 实现 排列组合

  • 77.组合

    题目给定两个整数 n 和 k,返回 1 ... n 中所有可能的 k 个数的组合。 示例:输入: n = 4, k...

  • 77.组合

    给定两个整数 n 和 k,返回 1 ... n 中所有可能的 k 个数的组合。示例:输入: n = 4, k = ...

  • 77.组合

    原题 https://leetcode-cn.com/problems/combinations/ 解题思路 典型...

  • 77. 组合

    https://leetcode-cn.com/problems/combinations/

网友评论

      本文标题:python实现leetcode之77. 组合

      本文链接:https://www.haomeiwen.com/subject/jmnowltx.html