题目链接(https://leetcode-cn.com/problems/permutations/submissions/)
题目描述
给定一个 没有重复 数字的序列,返回其所有可能的全排列。
示例
输入: [1,2,3]
输出:
[
[1,2,3],
[1,3,2],
[2,1,3],
[2,3,1],
[3,1,2],
[3,2,1]
]
思路
对给定数组进行搜索,搜索时注意不要搜索已在当前结果中存在的数字,当结果的长度达到数组长度时,将其放入最终结果的列表即可。
参考代码一(DFS)
class Solution:
def permute(self, nums: List[int]) -> List[List[int]]:
total_result = []
used_nums = {i:False for i in nums}
nums_len = len(nums)
def dfs(result, used_nums):
if len(result) == nums_len:
total_result.append(result)
for i in range(0, nums_len):
num = nums[i]
if used_nums[num]:
continue
else:
used_nums[num] = True
dfs(result+[num], used_nums)
used_nums[num] = False
dfs([], used_nums)
return total_result
参考代码二(BFS)
class Solution:
def permute(self, nums):
from collections import deque
root = []
deq = deque()
deq.append(root)
nums_len = len(nums)
total_result = []
while deq:
result = deq.popleft()
if len(result) == nums_len:
total_result.append(result)
continue
for i in nums:
if i not in result:
deq.append(result + [i])
return total_result