经典题了
https://leetcode.com/problems/permutations/
Given a collection of distinct integers, return all possible permutations.
Example:
Input: [1,2,3] Output: [ [1,2,3], [1,3,2], [2,1,3], [2,3,1], [3,1,2], [3,2,1] ]
这里提供三种思路
思路一,swap,in-place解决问题,这个应该是最优解吧
class Solution(object):
def permute(self,nums):
res=[]
self.helper(nums,res,0)
return res
def helper(self,nums,res,index):
if index==len(nums):
res.append(nums[:])
return
for i in range(index,len(nums)):
tmp=nums[i]
nums[i]=nums[index]
nums[index]=tmp
self.helper(nums,res,index+1)
tmp=nums[i]
nums[i]=nums[index]
nums[index]=tmp
注意的点有两个,helper function的for i in range(index,len(nums))这个要背下来,然后记得要swap两次。
思路二,普通dfs
class Solution(object):
def permute(self,nums):
res=[]
self.helper2(nums,res,[])
return res
def helper2(self,nums,res,cur):
if len(nums)==1:
cur+=[nums[0]]
res.append(cur[:])
return
for i,item in enumerate(nums):
self.helper2(nums[:i]+nums[i+1:],res,cur+[item])
注意的地方,提前一层返回。
思路三 python大法
class Solution(object):
def permute(self,nums):
return map(list,itertools.permutations(nums,len(nums)))
算下来,最后这个函数没有自己写的算法快。。。