給定一個沒有重複數字的序列,返回其全部可能的全排列。javascript
示例:java
輸入: [1,2,3]
輸出:
[
[1,2,3],
[1,3,2],
[2,1,3],
[2,3,1],
[3,1,2],
[3,2,1]
]
複製代碼
參考:spa
/** * @param {number[]} nums * @return {number[][]} */
var permute = function (nums) {
result = []
nums.sort(function (a, b) {
return a - b
})
find(nums, [])
return result
};
let result = []
function find(nums, templateList) {
if (nums.length == 0) {
result.push(templateList.slice())
}
for (let i = 0; i < nums.length; i++) {
templateList.push(nums[i])
let copy = nums.slice()
copy.splice(i, 1)
find(copy, templateList)
templateList.pop()
}
}
複製代碼