46. Permutations——本质和树DFS遍历无异 fun: for i in nums fun(i)
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]] """ ans = [] self.permute_helper(nums, 0, ans) return ans def permute_helper(self, nums, start, ans): if start == len(nums): ans.append(list(nums)) return for i in range(start, len(nums)): nums[i], nums[start] = nums[start], nums[i] self.permute_helper(nums, start+1, ans) nums[i], nums[start] = nums[start], nums[i]