[JS] Permutations

2022. 7. 31. 12:25

🔒 문제 (LeetCode 46)

Given an array nums of distinct integers, return all the possible permutations. You can return the answer in any order.

Constraints:

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

 

🌊 입출력

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

 


 

🔑 해결

🌌 알고리즘 - DFS (backtracking)

/**
 * @param {number[]} nums
 * @return {number[][]}
 */
var permute = function(nums) {
    const result = [];
    const len = nums.length;
    let visited = new Array(len).fill(false);

    function dfs(visited, cur) {
        if(cur.length === len) {
            result.push([...cur]);
            return;
        }
        
        
        for(let i = 0; i < len; i++) {
            if(visited[i]) continue;
            
            cur.push(nums[i]);
            visited[i] = true;
            
            dfs(visited, cur);
            
            cur.pop();
            visited[i] = false;
        }
    }
    
    dfs(visited, []);
    
    return result;
};

'코딩테스트 (JS) > DFS | BFS' 카테고리의 다른 글

[JS] Number of Islands  (0) 2022.08.12
[JS] Letter Case Permutation  (0) 2022.07.31
[JS] Combinations  (0) 2022.07.31
[JS] Rotting Oranges  (0) 2022.07.30
[JS] 01 Matrix  (0) 2022.07.30

+ Recent posts