给定一个不含重复数字的数组 nums ,返回其 所有可能的全排列 。你可以 按任意顺序 返回答案。
示例 1:
输入:nums = [1,2,3]
输出:[[1,2,3],[1,3,2],[2,1,3],[2,3,1],[3,1,2],[3,2,1]]
示例 2:
输入:nums = [0,1]
输出:[[0,1],[1,0]]
示例 3:
输入:nums = [1]
输出:[[1]]
提示:
1 <= nums.length <= 6
-10 <= nums[i] <= 10
nums 中的所有整数 互不相同
来源:力扣(LeetCode)
链接:https://leetcode-cn.com/problems/permutations
参考:
python
# 0046.全排列
class Solution:
def permute(self, nums: [int]) -> [[int]]:
res = []
path = []
used = [] # 存放已经使用过的数字
def track(nums, used):
if len(path) == len(nums):
return res.append(path[:])
for i in range(0, len(nums)):
if nums[i] in used:
continue # used中已收录,跳过
path.append(nums[i])
used.append(nums[i])
track(nums, used)
used.pop()
path.pop()
track(nums, used)
return res
# 不使用used记录使用的元素
class Solution:
def permute(self, nums: [int]) -> [[int]]:
res = []
path = []
def track(nums):
if len(path) == len(nums):
return res.append(path[:])
for i in range(0, len(nums)):
if nums[i] in path:
continue
path.append(nums[i])
track(nums)
path.pop()
track(nums)
return res
golang
package backTrack
var res [][]int
func permute(nums []int) [][]int {
res = [][]int{}
track(nums, len(nums), []int{})
return res
}
func track(nums []int, length int, path []int) {
if len(nums) == 0 {
p := make([]int, len(path))
copy(p, path)
res = append(res, p)
}
for i:=0;i<length;i++ {
cur := nums[i]
path = append(path, cur)
nums = append(nums[:i], nums[i+1:]...)
track(nums, len(nums), path)
nums = append(nums[:i], append([]int{}, nums[i:]...)...)
path = path[:len(path)-1]
}
}