【LeetCode】46 全排列

xiaoxiao2021-02-28  34

题目介绍

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

示例:

输入: [1,2,3] 输出: [ [1,2,3], [1,3,2], [2,1,3], [2,3,1], [3,1,2], [3,2,1] ]

题目理解

本题目就是在原有的列表基础上,完成一次全排列,看样例输入输出能够理解题意,考虑到的解法是用递归的思路,一遍一遍的赋值给目标结果,当满足可以赋值的情况时就赋值。

代码实现(py)

import copy res = [] class Solution(object): def permute(self, nums): """ :type nums: List[int] :rtype: List[List[int]] """ res.clear() if len(nums) == 0: return [] if len(nums) == 1: return [nums] for i in range(len(nums)): self.permuteHelper([nums[i]], nums[0:i] + nums[i + 1:]) return res def permuteHelper(self, before, nums): now = copy.copy(before) if len(nums) == 1: now.append(nums[0]) res.append(now) else: for i in range(len(nums)): now.append(nums[i]) self.permuteHelper(now, nums[0:i] + nums[i + 1:]) now.remove(nums[i])使用一个辅助函数来帮忙递归调用。其中需要注意的是:list的复制需要注意复制的问题,很关键。。。
转载请注明原文地址: https://www.6miu.com/read-2627525.html

最新回复(0)