Promble
link: https://leetcode.com/problems/permutations/
Given an array nums of distinct integers, return all the possible permutations. You can return the answer in any order.
Input: nums = [1,2,3]
Output: [[1,2,3],[1,3,2],[2,1,3],[2,3,1],[3,1,2],[3,2,1]]
Input: nums = [0,1]
Output: [[0,1],[1,0]]
Input: nums = [1]
Output: [[1]]
Approach 1
use itertools libs.
Thought
- return list(permutations(nums)) 📓 permutations need to use list to return.
Code
from itertools import permutations
class Solution:
def permute(self, nums: List[int]) -> List[List[int]]:
return list(permutations(nums))
Approach 2
back track
Thought
- def ans:list to store the final result.
- def backtrack, var curr:list is ans.
- first the ans is []
- judge if len(curr) == len(nums): ans.append(curr[:]) return
- loop num in nums:
- if num not in curr: curr.append(num)
- recurrence backtrack
- curr.pop()
- the final result is ans.
Code
class Solution:
def permute(self, nums: List[int]) -> List[List[int]]:
def backtrack(curr):
if len(curr) == len(nums):
ans.append(curr[:])
return
for num in nums:
if num not in curr:
curr.append(num)
backtrack(curr)
curr.pop()
ans = []
backtrack([])
return ans
Approach 3
dfs method.
Thought
- permutations:list store the final result.
- into self.dfs(nums, permutation, visited, permutations)
- return the permutations
dfs:
- def dfs(nums, permutations, visited, permutations) nums is the list, permutations is the list to temp store the num in nums, visited to store the visited num, permutations is the final result.
- first judge if len(nums) == len(permutations): permutations.append(llist(permutation)), return # change the state
- loop num in nums
- judge if num in visited: continue;
- add num into permutation
- add num into visited, because it also visited
- recurrence the self.dfs function.
- remove the num from visited.
- pop last num from permutation.
Code
class Solution:
def permute(self, nums: List[int]) -> List[List[int]]:
if not nums:
return [[]]
permutations = []
self.dfs(nums, [], set(), permutations)
return permutations
def dfs(self, nums, permutation, visited, permutations):
if len(nums) == len(permutation):
permutations.append(list(permutation))
return
for num in nums:
if num in visited:
continue;
permutation.append(num)
visited.add(num)
self.dfs(nums, permutation, visited, permutations)
visited.remove(num)
permutation.pop()