Leetcode 46. Permutations

Daehwi Kim·2021년 7월 9일

문제

46. Permutations

Medium


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.

 

풀이


itertools 내장 모듈을 이용한 풀이

class Solution:
    def permute(self, nums: List[int]) -> List[List[int]]:
        
        result = itertools.permutations(nums, len(nums))
        
        return result

위의 문제는 중복되지 않는 모든 수열을 찾는 문제로서, Python의 내장모듈 itertools.permutations 메소드를 이용하여 쉽게 모든 순열의 리스트를 찾을 수 있다.

dfs의 백트래킹을 이용한 풀이

class Solution:
    def permute(self, nums: List[int]) -> List[List[int]]:
    	# 모든순열의 리스트 초기화
        result = []
        # 각 순열 리스트 초기화
        prev_lst = []
        
        # dfs 탐색
        def dfs(elements):
        	# base case
            if len(elements) == 0:
            	# prev_list를 append하면 prev_list의 결과값을 참조하는 것이 아니라 
                # prev_list에 대한 참조가 추가된다.
                # 그래서 prev_list를 카피떠서 추가한다.
                result.append(prev_lst[:])
                return
            
            for e in elements:
                next_elements = elements[:]
                next_elements.remove(e)
                
                prev_lst.append(e)
                dfs(next_elements)
                prev_lst.pop()
        
        dfs(nums)
        
        return result
  • dfs탐색과 백트래킹을 이용하여 모든 순열을 찾는 풀이이다.

profile
게으른 개발자

3개의 댓글

comment-user-thumbnail
2022년 1월 12일

안녕하세요! 혹시 리트코드를 쓰시는 이유가 있을까요? 영어라서 쓸까말까 고민중인데 쓸만한가 해서요

1개의 답글