【Leetcode】46—Permutations

一、题目描述

给定一个没有重复数字的序列,返回其所有可能的全排列。
示例:

输入: [1,2,3]
输出:
[
  [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]]
        """
        
        finallen = len(nums)
        
        def dfs(nums, cur, res):
            if len(cur) == finallen: 
                res.append(cur)
                return
            for index, num in enumerate(nums):
                dfs(nums[:index] + nums[index+1:], cur + [num], res)
        
        res = []
        cur = []
        for index, num in enumerate(nums):
            dfs(nums[:index] + nums[index+1:], cur + [num], res)
            
        return res

你可能感兴趣的:(【Leetcode】46—Permutations)