题目链接:https://leetcode-cn.com/problems/permutations/
python3实现:
class Solution(object):
def permute(self, nums):
"""
:type nums: List[int]
:rtype: List[List[int]]
"""
rs = []
def swap(i, j):
t = nums[i]
nums[i] = nums[j]
nums[j] = t
def permu(arr, p, q):
if p == q:
rs.append(arr[:q + 1])
else:
for i in range(p, len(arr)):
swap(p, i)
permu(arr, p + 1, q)
swap(p, i)
permu(nums, 0, len(nums)-1)
return rs
class Solution:
def permute(self, nums: List[int]) -> List[List[int]]:
res = []
def backtrack(nums, tmp):
if not nums:
res.append(tmp)
return
for i in range(len(nums)):
backtrack(nums[:i] + nums[i+1:], tmp + [nums[i]])
backtrack(nums, [])
return res
python3实现:
def swap(i, j):
t = nums[i]
nums[i] = nums[j]
nums[j] = t
def permu(arr, p, q):
if p == q:
print(arr[:q + 1])
else:
for i in range(p, len(arr)):
swap(p, i)
permu(arr, p + 1, q)
swap(p, i)
rs = []
nums = [1, 2, 3]
permu(nums, 0, len(nums) - 1)
JavaScript实现:
function swap(arr, i, j) {
let t = arr[i]
arr[i] = arr[j]
arr[j] = t
}
function permu(arr, p, q) {
if (p === q) {
console.log(arr)
}
for (let i = p; i <= q; i++) {
swap(arr, p, i)
permu(arr, p + 1, q)
swap(p, i)
}
}
let nums = [1, 2, 3, 4, 5]
permu(nums, 0, nums.length - 1)
javascript版LeetCode提交
/**
* @param {number[]} nums
* @return {number[][]}
*/
var permute = function(nums) {
let result = []
function swap(nums, i, j) {
let t = nums[i]
nums[i] = nums[j]
nums[j] = t
}
function f(nums, start, end) {
if (start === end) {
// return nums[start]
let temp = []
nums.forEach(v => {
temp.push(v)
})
result.push(temp)
// console.log(result)
}
for (let i = start; i <= end; i++) {
swap(nums, start, i)
f(nums, start + 1, end)
// console.log(nums)
swap(nums, start, i)
}
// return result
}
f(nums, 0, nums.length - 1)
return result
};
let nums = [1, 2, 3]
let rs = permute(nums)
console.log(rs)
参考链接:https://www.bilibili.com/video/av9830088?from=search&seid=7879611443496777902