본문 바로가기

알고리즘 스터디

[Leetcode/파이썬] 46. Permutations

반응형

Permutations

Difficulty: 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.
class Solution:
    def permute(self, nums: List[int]) -> List[List[int]]:
        result = []  # 결과를 저장할 리스트

        # 백트래킹을 위한 헬퍼 함수 정의
        def backtrack(start):
            # 기본 케이스: 모든 숫자를 사용하여 하나의 순열을 완성한 경우
            if start == len(nums):
                result.append(nums[:])  # 현재 순열을 결과 리스트에 추가
                return

            # 순열을 생성하기 위해 start부터 끝까지 각 숫자를 순서대로 시도
            for i in range(start, len(nums)):
                nums[start], nums[i] = nums[i], nums[start]  # 현재 위치와 i 위치의 숫자를 교환
                backtrack(start + 1)  # 다음 위치에 대해 백트래킹 호출
                nums[start], nums[i] = nums[i], nums[start]  # 교환한 숫자를 원래 위치로 복원

        backtrack(0)  # 백트래킹 함수 호출 시작, 시작 위치는 0
        return result  # 결과 리스트 반환

Permutation 라이브러리를 구현하는 문제인 듯 하다. 예전에 풀었는데 다시 푸니까 못풀고 있다... 백트래킹 이렇게 쓰자. 문제인 듯 하다. 

반응형