https://leetcode.com/problems/permutations/description/
LeetCode - The World's Leading Online Programming Learning Platform
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
아이디어
순열을 구하는 문제였다!
두 가지 방법으로 풀었다.
1. 파이썬 제너레이터 사용
class Solution:
def permute(self, nums: List[int]) -> List[List[int]]:
def helper(prefix, num):
if not num:
yield prefix
for i, n in enumerate(num):
yield from helper(prefix + [n], num[:i]+num[i+1:])
return list(helper([], nums))
2. DFS 사용
class Solution:
def permute(self, nums: List[int]) -> List[List[int]]:
answer = []
def dfs(prefix, num):
if not num:
answer.append(prefix)
return
for i, n in enumerate(num):
dfs(prefix + [n], num[:i]+num[i+1:])
dfs([], nums)
return answer
두 가지를 비교하면 DFS가 더 적은 빠른 것을 알 수 있다 :3
'Coding Test > Python' 카테고리의 다른 글
[백준/union-find] 1717번: 집합의 표현(골드5, python) (0) | 2024.02.15 |
---|---|
[LeetCode] 47. Permutations II (Medium, Python) (1) | 2024.02.14 |
[백준/구현] 20057번: 마법사 상어와 토네이도(골드3, python) (1) | 2024.02.09 |
[프로그래머스/GREEDY] 구명보트 (level2, python) (0) | 2024.02.04 |
[백준/구현] 1268번: 임시 반장 정하기 (브론즈1, python) (0) | 2024.02.02 |