【力扣】全排列
来源:力扣(LeetCode)
链接:https://leetcode-cn.com/problems/permutations
给定一个 没有重复 数字的序列,返回其所有可能的全排列。
示例:
输入: [1,2,3]
输出:
[
[1,2,3],
[1,3,2],
[2,1,3],
[2,3,1],
[3,1,2],
[3,2,1]
]
1 class Solution: 2 def permute(self, nums: List[int]) -> List[List[int]]: 3 a = [] 4 b = [] 5 tem = nums 6 7 8 def quanpai(index,other): 9 if other == []: 10 a.append(index) 11 return 12 for i in range(len(other)): 13 tmp2 = other 14 b.append(index) 15 other1 = tmp2 - list(other.pop(i)) 16 z = b.append(other[i]) 17 quanpai(b,other1) 18 19 for i in range(len(nums)): 20 other = tem - [nums.pop(i)] 21 quanpai(nums[i],other) 22
第20行 list与list不能相减了,卡在这里。实在不知道怎么办了,other想要表示一个去掉了num[i]的列表,用b记录一路下来的元素,全部遍历完就可以把这一个路径添加入a中,本质上是广度优先搜索。
-----------------------------------------------------------------------
作者:LeetCode-Solution
链接:https://leetcode-cn.com/problems/permutations/solution/quan-pai-lie-by-leetcode-solution-2/
来源:力扣(LeetCode)
树形问题上的深度优先搜索,又被称作回溯算法,深度优先搜索本质上就是在列表最后添加或删除元素,所以“栈”是最好的数据结构的选择。
方法一:回溯
思路和算法
这个问题可以看作有 n个排列成一行的空格,我们需要从左往右依此填入题目给定的 n 个数,每个数只能使用一次。那么很直接的可以想到一种穷举的算法,即从左往右每一个位置都依此尝试填入一个数,看能不能填完这 n 个空格,在程序中我们可以用「回溯法」来模拟这个过程。
1 class Solution: 2 def permute(self, nums: List[int]) -> List[List[int]]: 3 res = [] 4 def backtrack(nums, tmp): 5 if not nums: 6 res.append(tmp) 7 return 8 for i in range(len(nums)): 9 backtrack(nums[:i] + nums[i+1:], tmp + [nums[i]]) 10 backtrack(nums, []) 11 return res 12 13 作者:powcai 14 链接:https://leetcode-cn.com/problems/permutations/solution/hui-su-suan-fa-by-powcai-2/ 15 来源:力扣(LeetCode)
我也想过把nums分开,但是害怕边界出错.....还真是这样干的。
官方把list分左右两部分
1 class Solution: 2 def permute(self, nums): 3 """ 4 :type nums: List[int] 5 :rtype: List[List[int]] 6 """ 7 def backtrack(first = 0): 8 # 所有数都填完了 9 if first == n: 10 res.append(nums[:]) 11 for i in range(first, n): 12 # 动态维护数组 13 nums[first], nums[i] = nums[i], nums[first] 14 # 继续递归填下一个数 15 backtrack(first + 1) 16 # 撤销操作 17 nums[first], nums[i] = nums[i], nums[first] 18 19 n = len(nums) 20 res = [] 21 backtrack() 22 return res 23 24 作者:LeetCode-Solution 25 链接:https://leetcode-cn.com/problems/permutations/solution/quan-pai-lie-by-leetcode-solution-2/ 26 来源:力扣(LeetCode)
浙公网安备 33010602011771号