欣迪

出處: 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 nums are 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
};

訂閱 IT-Monk

訂閱最新文章的發布消息! 😚😚😚
Loading

作者介紹 - 欣迪

欣迪

從設計到寫程式,發現自己有追求前端技巧的自虐傾向。不斷的踩坑,再從坑裡爬出來,慢慢對攀岩有點心得。 目前在多間公司擔任網站設計顧問。 同時也是網站架設公司負責人。