m1ndy5's coding blog

LeetCode 46.Permutations(순열) with Python 본문

알고리즘 with python/알고리즘 스터디

LeetCode 46.Permutations(순열) with Python

정민됴 2024. 1. 10. 10:04

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

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

        def dfs(pair, n):
            if len(pair) == n:
                answer.append(pair[:])
                return

            for i in nums:
                if i not in pair:
                    pair.append(i)
                    dfs(pair, n)
                    pair.pop()

        dfs([], len(nums))

        return answer

간단하게 라이브러리 사용해서 풀기

import itertools

def permute(self, nums):
    return list(itertools.permutations(nums))

itertools 모듈을 쓰면 아주 간단하게 표현 가능하다.
근데 라이브러리 쓰지 말고 직접 풀어보라고 명시하는 곳도 있다고 들어서 일단 나는 잘 사용안하려고 하긴하는데
별도의 제약사항이 없다면 구현의 효율성 및 성능 개선을 위해 사용하는 것이 좋다고 한다.