leetcode力扣77. 组合

给定两个整数 n 和 k,返回 1 ... n 中所有可能的 k 个数的组合。

示例:

输入: n = 4, k = 2
输出:
[
  [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]]
        """
        ress = []
        def backtrack(res = [],begin = 1):
            if len(res) == k:
                ress.append(res[:])
            for i in range(begin,n+1):
                res.append(i)
                backtrack(res,i+1)
                res.pop()

        backtrack()
        return ress
发布了332 篇原创文章 · 获赞 170 · 访问量 50万+

猜你喜欢

转载自blog.csdn.net/qq_32146369/article/details/104127092
今日推荐