题目描述:
给定一个不含重复数字的数组 nums
,返回其 所有可能的全排列 。你可以 按任意顺序 返回答案。
示例 1:
输入:nums = [1,2,3] 输出:[[1,2,3],[1,3,2],[2,1,3],[2,3,1],[3,1,2],[3,2,1]]示例 2:
输入:nums = [0,1] 输出:[[0,1],[1,0]]示例 3:
输入:nums = [1] 输出:[[1]]
思路:
整体是采用递归的方式,通过调整visited列表的内容来控制road的值,偏模板
代码:
class Solution(object):def permute(self, nums):""":type nums: List[int]:rtype: List[List[int]]"""# 判空if not nums:return []# visited初始化为Falsevisited = [False] * len(nums)res = []def dfs(res, visited, road, deep):# 递归边界if deep == len(nums):res.append(road[:])for i in range(len(nums)):if not visited[i]:visited[i] = Trueroad.append(nums[i])dfs(res, visited, road, deep + 1)road.pop()visited[i] = Falsedfs(res, visited, [], 0)return resif __name__ == "__main__":nums = [1, 2, 3]a = Solution()res = a.permute(nums)print(res)