打卡群刷题总结0723——组合

时间:2022-07-22
本文章向大家介绍打卡群刷题总结0723——组合,主要内容包括其使用实例、应用技巧、基本知识点总结和需要注意事项,具有一定的参考价值,需要的朋友可以参考一下。

题目:77. 组合

链接:https://leetcode-cn.com/problems/combinations

给定两个整数 n 和 k,返回 1 ... n 中所有可能的 k 个数的组合。 示例: 输入: n = 4, k = 2 输出: [ [2,4], [3,4], [2,3], [1,2], [1,3], [1,4], ]

解题:

1、DFS回溯。

代码:

class Solution(object):
    def _combine_helper(self, start, k, current):
        if k == 0:
            self.res.append(current)
            return 
        for i in range(start, len(self.num) - k + 1):
            current2 = copy.copy(current)
            current2.append(self.num[i])
            self._combine_helper(i + 1, k - 1, current2)

    def combine(self, n, k):
        """
        :type n: int
        :type k: int
        :rtype: List[List[int]]
        """
        self.num = list(range(1, n + 1))
        self.res = []
        self._combine_helper(0, k, [])
        return self.res

PS:刷了打卡群的题,再刷另一道题,并且总结,确实耗费很多时间。如果时间不够,以后的更新会总结打卡群的题。

PPS:还是得日更呀,总结一下总是好的。