LeetCode | 0077. Combinations組合【Python】

LeetCode 0077. Combinations組合【Medium】【Python】【回溯】

Problem

LeetCode

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],
]

問題

力扣

給定兩個整數 n 和 k,返回 1

if name == "__main… n 中所有可能的 k 個數的組合。

示例:

輸入: n = 4, k = 2
輸出:
[
  [2,4],
  [3,4],
  [2,3],
  [1,2],
  [1,3],
  [1,4],
]

思路

回溯

回溯三步驟
1.有效結果:path 長度等於 k。
2.回溯範圍及答案更新。
3.剪枝條件:經過分析,可以發現 i 應該 <= n - (k - len(path)) + 1。
詳細分析可以參考 liweiwei1419 的題解(在最後)。
Python3代碼
class Solution:
    def combine(self, n: int, k: int) -> List[List[int]]:
        # special judgment
        if n <= 0 or k <= 0 or k > n:
            return []
        
        res = []
        self.dfs(1, k, n, [], res)
        return res
    
    def dfs(self, start, k, n, path, res):
        # 1.valid result
        if len(path) == k:
            res.append(path[:])
            return
        
        # 3.pruning
        for i in range(start, n - (k - len(path)) + 2):
            # 2.backtrack and update
            path.append(i)
            self.dfs(i + 1, k, n, path, res)
            path.pop()

代碼地址

GitHub鏈接

參考

liweiwei1419 題解

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章