视频学习记录
https://www.bilibili.com/video/BV1xG4y1F7nC
例题和课后作业代码记录 77. 组合
https://leetcode.cn/problems/combinations/description/
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 class Solution : def combine (self, n: int , k: int ) -> List [List [int ]]: ans = [] path = [] def dfs (i:int , select_num:int ): nonlocal ans, path if select_num == k: ans.append(path.copy()) return for num in range (i, k-select_num-1 , -1 ): path.append(num) dfs(num-1 , select_num+1 ) path.pop() dfs(n, 0 ) return ans
216. 组合总和 III
https://leetcode.cn/problems/combination-sum-iii/description/
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 class Solution : def combinationSum3 (self, k: int , n: int ) -> List [List [int ]]: ans = [] path = [] def dfs (index:int , left_n:int ): nonlocal ans, path left_k = len (path)-k if left_k == 0 or left_n <= 0 : if left_n == 0 and left_k == 0 : ans.append(path.copy()) return for i in range (index, left_k-1 , -1 ): path.append(i) dfs(i-1 , left_n-i) path.pop() dfs(9 , n) return ans
22. 括号生成
https://leetcode.cn/problems/generate-parentheses/description/
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 class Solution : def generateParenthesis (self, n: int ) -> List [str ]: ans = [] full_len = 2 *n def dfs (path:str , left:int ): if len (path) == full_len: ans.append(path) return if left < n: dfs(path+"(" , left+1 ) right = len (path)-left if right < left: dfs(path+")" , left) dfs("" , 0 ) return ans
39. 组合总和
https://leetcode.cn/problems/combination-sum/description/
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 class Solution : def combinationSum (self, candidates: List [int ], target: int ) -> List [List [int ]]: candidates.sort() ans = [] path = [] def dfs (cur_sum:int , start_index:int ): if cur_sum == target: ans.append(path.copy()) return for i, num in enumerate (candidates[start_index:]): if cur_sum + num > target: break path.append(num) dfs(cur_sum+num, start_index+i) path.pop() dfs(0 , 0 ) return ans