classSolution: defgenerateParenthesis(self, n: int) -> List[str]: res = [] cur = "" defdfs(left, right, cur): if left==0and right==0: res.append(cur) return if left>right: return if left>0: # 注意 dfs(left-1,right,cur+"(") if right>0: dfs(left, right-1,cur+")") dfs(n,n,cur) return res
classSolution: defgenerateParenthesis(self, n: int) -> List[str]: res = []
defback(state, left, right): if left == 0and right == 0: res.append("".join(state[:])) return if left > right: return if left > 0: state.append("(") back(state, left - 1, right) state.pop() if right > 0: state.append(")") back(state, left, right - 1) state.pop()
classSolution: defisPossible(self, nums: List[int]) -> bool: defif_increase(nums2): iflen(nums2)<3: returnFalse for i inrange(len(nums2)-1): ifnot nums2[i+1] - nums2[i]==1: returnFalse returnTrue if if_increase(nums): returnTrue for lens inrange(3, len(nums)): left = [] right = [] for i in nums: ifnot left or i - left[-1] == 1andlen(left) < lens: left.append(i) else: right.append(i) if self.isPossible(left) and self.isPossible(right): returnTrue returnFalse
defback(state, s, index): iflen(state) == len(nums): if s == target: if"".join(state) notin sets: sets.add("".join(state[:])) return return for i inrange(index, len(nums)): state.append("+1") s = s + nums[i] back(state, s, i + 1) s = s - nums[i] state.pop()
s = s - nums[i] state.append("-1") back(state, s, i + 1) s = s + nums[i] state.pop()
defback(state, index): if xxx: res.append(xxx) return for i inrange(index, len(xxx)): # 需要的话这里加上剪枝 if index>i and used[i]==used[i-1]: continue state.append(nums[i] 或者 nums[i, index]) back(state, i+1) #这里注意是i+1还是index+1的呢 state.pop()
nums.sort() # 注意点 res = [] defback(state, index): res.append(state[:]) for i inrange(index, len(nums)): if i>index and nums[i]==nums[i-1]:# 注意点 continue state.append(nums[i]) back(state, i+1) # 注意点 state.pop() back([], 0) return res
classSolution: defexist(self, board: List[List[str]], word: str) -> bool: m = len(board) n = len(board[0])
visited = [[0]*n for _ inrange(m)] defhelper(row, col, index): if index == len(word): # returnTrue for delta_x, delta_y in [(0,1),(0,-1),(1,0),(-1,0)]: new_row = row + delta_x new_col = col + delta_y if0<=new_row<m and0<=new_col<n andnot visited[new_row][new_col] and board[new_row][new_col]==word[index]: visited[new_row][new_col]=1# if helper(new_row,new_col,index+1): # returnTrue visited[new_row][new_col]=0 returnFalse for i inrange(m): for j inrange(n): if board[i][j]==word[0]: visited[i][j]=1# if helper(i,j,1): returnTrue else: # visited[i][j] = 0 returnFalse
classSolution: defis_check(self, state, row, col, n): # 检查行 for row1 inrange(n): if state[row1][col] == 'Q': returnFalse # 检查列 for col1 inrange(n): if state[row][col1] == "Q": returnFalse # 检查135度方向 row1, col1 = row, col for i inrange(n): row1 -= 1 col1 -= 1 if row1 >= 0and col1 >= 0: if state[row1][col1] == "Q": returnFalse # 检查45度方向 row1, col1 = row, col for i inrange(n): row1 -= 1 col1 += 1 if row1 >= 0and col1 <= n-1: if state[row1][col1] == "Q": returnFalse returnTrue
defsolveNQueens(self, n: int) -> List[List[str]]: res = [] init_state = [['.'] * n for _ inrange(n)]
defback(state, row): if row == n: res.append([''.join(i) for i in state]) return for col inrange(n): if self.is_check(state, row, col, n): state[row][col] = 'Q' back(state, row + 1) state[row][col] = "." back(init_state, 0) return res
classSolution: defis_valid(self, row: int, col: int, val: int, board): # 判断同一行是否冲突 for i inrange(9): if board[row][i] == str(val): returnFalse # 判断同一列是否冲突 for j inrange(9): if board[j][col] == str(val): returnFalse # 判断同一九宫格是否有冲突 start_row = (row // 3) * 3 start_col = (col // 3) * 3 for i inrange(start_row, start_row + 3): for j inrange(start_col, start_col + 3): if board[i][j] == str(val): returnFalse returnTrue
defsolveSudoku(self, board): """ Do not return anything, modify board in-place instead. """
defback(state): for row inrange(len(board)): for col inrange(len(board[0])): if board[row][col] != '.': continue for k inrange(1, 10): if self.is_valid(row, col, k, state): state[row][col] = str(k) if back(state): returnTrue state[row][col] = "." returnFalse returnTrue back(board)
和单词搜索很像,虽然那道题我也用了以往回溯的思路
所有可能得路径[797]
严格意义上不算这类问题,但是仔细看,也是发现有回溯的性质在里面,题解如下:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16
classSolution: defallPathsSourceTarget(self, graph: List[List[int]]) -> List[List[int]]: res = [] defback(state, index): if index == len(graph) - 1: res.append(state[:]) return for i inrange(len(graph[index])): state.append(graph[index][i]) back(state, graph[index][i]) state.pop() state = [0] back(state, 0) return res
classSolution: defmaxAreaOfIsland(self, grid: List[List[int]]) -> int: defdfs(grid, i, j,current_res): if grid[i][j]==0: return current_res[0]= current_res[0]+1 grid[i][j] = 0 for delta_x, delta_y in [(0,1),(0,-1),(-1,0),(1,0)]: new_i = i + delta_x new_j = j + delta_y if new_i>=0and new_i<len(grid) and new_j>=0and new_j<len(grid[0]): dfs(grid, new_i, new_j, current_res)
res = 0 for i inrange(len(grid)): for j inrange(len(grid[0])): if grid[i][j]==1: current_res = [0] # 注意 dfs(grid,i,j,current_res) res = max(res, current_res[0]) return res
岛屿的周长[463]
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18
classSolution: defislandPerimeter(self, grid: List[List[int]]) -> int: defget_nb_nums(i,j): cnt = 0 for delta_x, delta_y in [(-1,0),(1,0),(0,1),(0,-1)]: new_i = i + delta_x new_j = j + delta_y if new_i>=0and new_i< len(grid) and new_j>=0and new_j<len(grid[0]) and grid[new_i][new_j]==1: cnt += 1 return cnt
res = 0 for i inrange(len(grid)): for j inrange(len(grid[0])): if grid[i][j] == 1: cur_bord = 4 - get_nb_nums(i,j) res = res + cur_bord return res
defdfs(x, y): ans = 1 mp[(x, y)] = idx for dx, dy in DIRS: if0 <= (nx := x + dx) < n and0 <= (ny := y + dy) < n and grid[nx][ny] and (nx, ny) notin mp: ans += dfs(nx, ny) return ans
for i inrange(n): for j inrange(n): if grid[i][j] and (i, j) notin mp: size_map[idx] = dfs(i, j) res = max(res, size_map[idx]) idx += 1
for i inrange(n): for j inrange(n): ifnot grid[i][j]: tmp, cur = set(), 1 for dx, dy in DIRS: if0 <= (nx := i + dx) < n and0 <= (ny := j + dy) < n and grid[nx][ny] and mp[(nx, ny)] notin tmp: tmp.add(mp[(nx, ny)]) cur += size_map[mp[(nx, ny)]] res = max(res, cur) return res