LeetCode-77. Combinations-python3解答

本文介绍了一个生成特定范围内k个数字组合的算法实现。通过递归方法,从1到n中选择k个数字的所有可能组合被列举出来。示例代码展示了如何使用Python实现这一功能,并返回所有可能的组合列表。

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

0.原题:

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

Example:

Input: n = 4, k = 2
Output:
[
  [2,4],
  [3,4],
  [2,3],
  [1,2],
  [1,3],
  [1,4],
]

 

1.代码

class Solution:
    def my_init(self,n,k):
        self.n = n
        self.k = k
        self.temp_result = [-1 for _ in range(k)]
        self.result = []
        self.visited = [False for _ in range(n)]

    def combine(self, n, k):
        """
        :type n: int
        :type k: int
        :rtype: List[List[int]]
        """
        self.my_init(n,k)
        self.fun(0,0)
        return self.result

    def fun(self,start,index):
        if index == self.k:
            r = self.temp_result.copy()
            self.result.append(r)
            return 0
        else:
            for i in range(start,self.n):
                self.temp_result[index] = i + 1
                self.fun(i+1,index+1)             
        return 0
        

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值