LeetCode-77. 組合【回溯】
- 題目描述:
- 解題思路一:回溯
- 背誦版
- 解題思路三:0
題目描述:
給定兩個整數 n 和 k,返回范圍 [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
解題思路一:回溯
代碼隨想錄
class Solution:def combine(self, n: int, k: int) -> List[List[int]]:res = []self.backtracking(n, k, 1, [], res)return resdef backtracking(self, n, k, startIndex, path, res):if len(path) == k:res.append(path[:])return for i in range(startIndex, n - (k - len(path)) + 2): # startIndex不能大于n - (k - len(path)) + 1,還需要的元素path.append(i)self.backtracking(n, k, i + 1, path, res)path.pop()
時間復雜度: O(n * 2^n)
空間復雜度: O(n)
背誦版
class Solution:def combine(self, n: int, k: int) -> List[List[int]]:res = []self.backtracking(n, k, 1, [], res)return resdef backtracking(self, n, k, start, path, res):if len(path) == k:res.append(path[:])return# for i in range(start, n - (k-len(path)) + 2): # 優化for i in range(start, n + 1):path.append(i)self.backtracking(n, k, i+1, path, res)path.pop()
時間復雜度: O(n * 2^n)
空間復雜度: O(n)
解題思路三:0
時間復雜度: O(n * 2^n)
空間復雜度: O(n)

? ⊕ ? ⊕ ? ⊕ ? ⊕ ? ⊕ ? ⊕ ? ⊕ ? ⊕ ? ⊕ ? ⊕ ? ⊕ ? ⊕ ? ⊕ ? ⊕ ? ⊕ ? ⊕ ? ⊕ ? ⊕ ? ⊕ ? ⊕ ? ⊕ ? ⊕ ? ⊕ ? ⊕ ? ⊕ ? ⊕ ? ⊕ ? ⊕ ? ⊕ ? ⊕ ?