Leetcode 46 Permutations
题目描述
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]
]
来源:力扣(LeetCode)
链接:https://leetcode-cn.com/problems/permutations
著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。
思路解析
这里采用字典序法,字典序法,代码如下
class Solution:
def permute(self, nums: List[int]) -> List[List[int]]:
if nums is None:
return [[]]
elif len(nums) <= 1:
return [nums]
nums.sort()
result = []
while True:
result.append([] + nums)
i = 0
for i in range(len(nums) - 2, -1, -1):
if nums[i] < nums[i + 1]:
break
elif i == 0:
return result
j = 0
for j in range(len(nums) - 1, i, -1):
if nums[i] < nums[j]:
break
nums[i], nums[j] = nums[j], nums[i]
nums[i + 1:] = nums[len(nums) - 1:i:-1]
return result
每道题背后的算法都够我们研究很久。
此外,回溯算法,待研究