[leetcode] 46. Permutations

불불이·2021년 1월 19일
0

매일 알고리즘

목록 보기
1/5

문제(DFS)

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
    시간 복잡도 6!
  • 10 <= nums[i] <= 10
    int안에 다 들어가는 범위
  • All the integers of nums are unique.
    똑같은 수 x

정답

var permute = (nums) => {
    const result = [];
    const current = [];

    backtracking(nums, result, current);
    console.log(result);
};

const backtracking = (nums, result, current) => {
    if (nums.length == current.length) {
        result.push(Array.from(current));
        return;
    }

    for (let i = 0; i < nums.length; i++) {
        if (current.includes(nums[i])) continue;
        current.push(nums[i]);
        backtracking(nums, result, current);
        current.pop();
    }
}

permute([1, 2, 3]);  

Review

  1. 문제를 안읽고 input output값만 보고 문제를 풀려했었다.
  2. 조건은 안읽었다.

profile
https://nibble2.tistory.com/ 둘 중에 어떤 플랫폼을 써야할지 아직도 고민중인 사람

1개의 댓글

comment-user-thumbnail
2021년 12월 25일

I found that solution is very popular and helpful: https://youtu.be/UvSPsz0jTQ4

답글 달기