出處: https://leetcode.com/problems/permutations/
Given an array nums of distinct integers, return all the possible permutations. You can return the answer in any order.
Example 1:
Input: nums = [1,2,3] Output: [[1,2,3],[1,3,2],[2,1,3],[2,3,1],[3,1,2],[3,2,1]]
Example 2:
Input: nums = [0,1] Output: [[0,1],[1,0]]
Example 3:
Input: nums = [1] Output: [[1]]
Constraints:
1 <= nums.length <= 6-10 <= nums[i] <= 10- All the integers of
numsare unique.
這題是找出所有的排列組合,再次使用遞迴方法來合成最後的答案:
/**
* @param {number[]} nums
* @return {number[][]}
*/
var permute = function(nums) {
// 只有一個數字時直接回輸入的陣列
if (nums.length === 1) return nums
// 用來搜集結果的陣列
const output = []
// 開始對逐個數字做 loop
for (let i = 0; i < nums.length; i++) {
// 做一個拿掉開頭數字的陣列
const _nums = nums.filter((item) => item !== nums[i])
// 開始丟進遞迴,取得 nums.length - 1 個數字的可能性
const orders = permute(_nums)
// 最後將回傳的結果,逐個在開頭加入 nums[i]
// 加入的結果網上會遞迴,直到最上層
for (let j = 0; j < orders.length; j++) {
output.push([nums[i], ...orders[j]])
}
}
return output
};
