본문 바로가기
🖥️ 문제 풀이/리트코드(Leetcode)

[LeetCode 해석 및 풀이] 46. Permutations(순열)

by 뒬탕 2024. 8. 6.
반응형

LeetCode 문제 해석 및 풀이 방법

 

문제 46. Permutations(순열)

난이도 : 중간🟡 바로가기

 

문제 설명

영문

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

 

한글

고유한 정수의 배열 nums 주어지면 가능한 모든 순열을 반환합니다. 어떤 순서 로든 답변을 반환할 수 있습니다.

 

제한조건

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

 

입출력 예

입력 출력
nums = [1,2,3] [[1,2,3],[1,3,2],[2,1,3],[2,3,1],[3,1,2],[3,2,1]]
nums = [0,1] [[0,1],[1,0]]
nums = [1] [[1]]

 

해답 및 해설

파이썬 (Python)

class Solution:
    def permute(self, nums: List[int]) -> List[List[int]]:
        n = len(nums)
        answer = []

        def swapHelper(arr, depth):
            if depth == n:
                answer.append(arr)
                return
            
            for i in range(depth, n):
                arr[depth], arr[i] = arr[i], arr[depth]
                swapHelper(arr.copy(), depth + 1)
                arr[depth], arr[i] = arr[i], arr[depth]
        
        swapHelper(nums, 0)

        return answer

 

원소를 스왑해가며 정하는 방식

https://programming4myself.tistory.com/94

 

🧮 순열 알고리즘 직접 구현!

순열과 중복순열 알고리즘을 파이썬으로 구현하기 순열이란? 원소들을 순서에 따라 나열하는 것 n개의 원소에서 r개를 나열한다 하면 그 가짓수는 n!/(n-r)! 중복해서 원소를 뽑으면 n^r 전체 순열

programming4myself.tistory.com

이 외의 순열을 푸는 방법은 해당 게시글에 올려두었다.

반응형

댓글