出處: https://leetcode.com/problems/permutations-ii/
Given a collection of numbers, nums
, that might contain duplicates, return all possible unique permutations in any order.
Example 1:
Input: nums = [1,1,2] Output: [[1,1,2], [1,2,1], [2,1,1]]
Example 2:
Input: nums = [1,2,3] Output: [[1,2,3],[1,3,2],[2,1,3],[2,3,1],[3,1,2],[3,2,1]]
Constraints:
1 <= nums.length <= 8
-10 <= nums[i] <= 10
相關題目: 解題 46. Permutations
一樣用遞迴處理:
/** * @param {number[]} nums * @return {number[][]} */ var permuteUnique = function(nums) { // 排除只有一個數字的狀態 if (nums.length === 1) return [nums] // 用來記錄結果的陣列 const res = [] // 用來記錄已經用過的數字 const Used = new Set() // 進入迴圈 for (let i = 0; i < nums.length; i++) { // 排除已經用過的數字 if (Used.has(nums[i])) continue // 如果數字沒用過 加入 Set Used.add(nums[i]) // 複製一個 nums const _nums = [...nums] // 排除本身的數字 _nums.splice(i, 1) // 進入下一個遞迴,並取得剩餘數字排列的結果 const _res = permuteUnique(_nums) // 把各種不同的組合加入 當前的數字 for (let j = 0; j < _res.length; j++) { res.push([nums[i], ..._res[j]]) } } // 回傳結果 return res };