46\. Permutations

# 46. Permutations (opens new window)

# Description

Difficulty: Medium

Related Topics: Array (opens new window), Backtracking (opens new window)

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]]
1
2

Example 2:

Input: nums = [0,1]
Output: [[0,1],[1,0]]
1
2

Example 3:

Input: nums = [1]
Output: [[1]]
1
2

Constraints:

  • 1 <= nums.length <= 6
  • -10 <= nums[i] <= 10
  • All the integers of nums are unique.

# Solution

Language: JavaScript

/**
 * @param {number[]} nums
 * @return {number[][]}
 * 广度优先遍历
 * 深度优先遍历
 */
var permute = function(nums) {
    nums.sort((a, b) => a - b);
    const ans = [];
    
    const backtrack = (path = []) => {
        if (path.length === nums.length) return ans.push([...path]);
        
        nums.forEach(num => {
            if (!path.includes(num)) backtrack([...path, num]);
        })
    }
    
    backtrack();
    
    return ans;
};
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
上次更新: 2022/7/14 下午7:06:25