首页 > 其他 > 详细

Leetcode - 77. 组合

时间:2021-09-11 19:10:06      阅读:19      评论:0      收藏:0      [点我收藏+]

给定两个整数nk,返回范围[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]]

提示:

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

来源:力扣(LeetCode)
链接:https://leetcode-cn.com/problems/combinations
著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。

解1 2021/9/10 O(?)

from itertools import combinations

def combine(n: int, k: int) -> list:
    res=[]
    l=[x for x in range(1,n+1)]
    for c in combinations(l,k):
        u=list(c)
        if u not in res:
            res.append(u)
    return res

if __name__ == ‘__main__‘:
    print(combine(4,2))
    print(combine(1,1))
    ### 错误
    # 1, 不能用permutations,得用combinations
    print(combine(3,3))

技术分享图片

Leetcode - 77. 组合

原文:https://www.cnblogs.com/Code2235/p/15250895.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!