【经典题目】【循环DFS】生成数组的全排列
问题描述
给你一个数组,生成这个数组中元素的全排列。
思路
经典的循环dfs。要点是我们需要设置visited数组来指代其是否被遍历过。
代码
class Solution: def islandPerimeter(self, grid): if not grid: return [] visited = [False for i in grid] res = [] def dfs(last): if len(last) == len(grid): res.append(last) for i in range(len(grid)): if not visited[i]: last += grid[i] visited[i] = True dfs(last) visited[i] = False last = last[:-1] dfs('') return res if __name__ == '__main__': s = Solution() print(s.islandPerimeter(['1', '2', '3', '4','5']).__len__())
经典变型:如果我们改一下题目,不生成全排列,而是固定长度的排列,那么我们只需要改一下last长度的判断条件即可。
class Solution: def islandPerimeter(self, grid, length): if not grid: return [] visited = [False for i in grid] res = [] def dfs(last): if len(last) == length: res.append(last) for i in range(len(grid)): if not visited[i]: last += grid[i] visited[i] = True dfs(last) visited[i] = False last = last[:-1] dfs('') return res if __name__ == '__main__': s = Solution() print(s.islandPerimeter(['1', '2', '3', '4','5'], 3))