[LeetCode] 46. Permutations_Medium tag: DFS, backtracking

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]
]

这个题目就是用for loop取nums的值,然后再recursive求去掉num之后的nums的permutation,再将两者组合 起来。

Code

class solution:
    def permutations(self, nums):
        ans = []
        def helper(ans, temp, nums):
            if not nums:
                ans.append(temp)
            else:
                for i in range(len(nums)):
                    helper(ans, temp + [nums[i]], nums[:i] + nums[i + 1:])
        helper(ans, [], nums)
        return ans

猜你喜欢

转载自www.cnblogs.com/Johnsonxiong/p/10916111.html
今日推荐