일하는/Algorithm, Coding

[LeetCode][릿코드][Python][#46] Permutations

김논리 2021. 11. 15. 13:13

https://leetcode.com/problems/permutations/

 

Permutations - LeetCode

Level up your coding skills and quickly land a job. This is the best place to expand your knowledge and get prepared for your next interview.

leetcode.com

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.

깊이 우선 탐색 (DFS: Depth-First Search) 방법을 사용하여 문제를 풀 수 있다.

아래와 같이 탐색하는 알고리즘을 구현한다.

 

class Solution:
    def permute(self, nums):
        result , visited = [], []
        def dfs(nums):
            if len(nums) == 0:
                result.append(visited[:])
            for num in nums:
                next = nums[:]
                next.remove(num)
                visited.append(num)
                dfs(next)
                visited.pop()

        dfs(nums)
        return result