Given a collection of distinct numbers, return all possible permutations.
For example,
[1,2,3]
have the following permutations:
[ [1,2,3], [1,3,2], [2,1,3], [2,3,1], [3,1,2], [3,2,1] ]
枚举所有的排列情况,和八皇后问题是一类,回溯的方式,或者深搜都是可行的
class Solution(object):
def permute(self, nums):
"""
:type nums: List[int]
:rtype: List[List[int]]
"""
res = []
self.dfs(res, [], nums)
return res
def dfs(self, res, numList, theNums):
if len(theNums) == 0:
res.append(list(numList))
for i in xrange(len(theNums)):
numList.append(theNums[i])
self.dfs(res, numList, theNums[:i] + theNums[i+1:])
numList.pop()