34 leetcode - Combinations

本文介绍了一个经典的组合问题:给定两个整数 n 和 k,返回所有可能的 k 个数的组合,这些数来自 1 到 n 的整数集合。例如当 n=4 且 k=2 时,解决方案包括 [2,4]、[3,4] 等。通过递归方法实现了这一算法,并提供了一个完整的 Python 代码示例。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

#!/usr/bin/python
# -*- coding: utf-8 -*-
'''
Combinations: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],  #左侧的数字要大于右侧
]
'''
class Solution(object):

    def combine(self, n, k):
        """
        :type n: int
        :type k: int
        :rtype: List[List[int]]
        """
        if k > n:
          return []
        ret = []
        self.__combine(n,k,1,0,range(k),ret)
        return ret

    def __combine(self,n,k,start_num,start_index,tmp,ret):
        if n - start_num + 1 < k - start_index:#小优化,如果剩余的数字的个数 < 要填充的个数,直接返回就好
            return
        if start_index == k:
            return ret.append(list(tmp))

        for i in range(start_num,n+1):
            tmp[start_index] = i
            self.__combine(n,k,i + 1,start_index + 1,tmp,ret)#右侧数字大于左侧数字,所以填充下一位时从左侧+1处开始即可

if __name__ == "__main__":
    s = Solution()
    print s.combine(4,2)
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值