classSolution(object): defsolveNQueens(self, n): """ :type n: int :rtype: List[List[str]] """ defdfs(cols_lst, xy_diff, xy_sum): cur_row = len(cols_lst) if cur_row == n: ress.append(cols_lst) for col inrange(n): if col notin cols_lst and cur_row - col notin xy_diff and cur_row + col notin xy_sum: dfs(cols_lst+[col], xy_diff+[cur_row-col], xy_sum+[cur_row+col]) ress = [] dfs([], [], []) return [['.' * i + 'Q' + '.' * (n-i-1) for i in res] for res in ress]
classSolution(object): deftotalNQueens(self, n): """ :type n: int :rtype: int """ defdfs(col_list,xy_diff,xy_sum): cur_row = len(col_list) if cur_row == n: ress.append(col_list) for col inrange(n): if col notin col_list and cur_row-col notin xy_diff and cur_row+col notin xy_sum: dfs(col_list+[col],xy_diff+[cur_row-col],xy_sum+[cur_row+col]) ress = [] dfs([],[],[]) returnlen(ress)
classSolution(object): defspiralOrder(self, matrix): """ :type matrix: List[List[int]] :rtype: List[int] """ ifnot matrix: return [] R = len(matrix) C = len(matrix[0]) seen = [[False]*C for _ in matrix] dr = [0,1,0,-1] dc = [1,0,-1,0] r = c = di = 0 ans = [] for _ inrange(R*C): ans.append(matrix[r][c]) seen[r][c] = True next_r,next_c = r+dr[di],c+dc[di] if0<= next_r < R and0<= next_c < C andnot seen[next_r][next_c]: r = next_r c = next_c else: di = (di+1)%4 r = r + dr[di] c = c + dc[di] return ans
classSolution(object): defcanJump(self, nums): """ :type nums: List[int] :rtype: bool """ last = len(nums)-1 for i inrange(len(nums)-1,-1,-1): if i + nums[i] >= last: last = i return last == 0