77. Combinations

77. Combinations

Medium

218281Add to ListShare

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

You may return the answer in any order.

 

Example 1:

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

Example 2:

Input: n = 1, k = 1
Output: [[1]]

 

Constraints:

  • 1 <= n <= 20
  • 1 <= k <= n

我的:440ms

class Solution:
    def combine(self, n: int, k: int) -> List[List[int]]:
        """
        解题思路:搜索题
        """
        result = []

        def dfs(i: int, cur_list: List[int]) -> None:
            if len(cur_list) >= k:
                result.append(list(cur_list))
                return
            if i > n:
                return

            for j in range(i, n + 1):
                cur_list.append(j)
                dfs(j + 1, cur_list)
                cur_list.pop()

        dfs(1, [])

        return result

 参考答案1:76ms

 

from itertools import combinations

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

  参考答案2:100ms

class Solution:
    def combine(self, n: int, k: int) -> List[List[int]]:
        """
        :type n: int
        :type k: int
        :rtype: List[List[int]]
        """
        def helper(n,k,start):
            # base case: need only one element
            if k == 1:
                return [[i] for i in range(start,n+1)]
            result = []
            for i in range(start,n-k+2):
                L = helper(n,k-1,i+1)
                for j in L:
                    result.append([i]+j)
            return result
        
        return helper(n,k,1)

 

 

评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值