- Reference
not in
μ μ¬μ©νλ κ²λ³΄λ€ dfsμ μ μμΈ visited
λ‘μ§μ μ¬μ©νλ κ² λ λΉ λ¦
- λμ ,
index
κ° μ΄μ© μ μμ΄ νμν΄μ§
Solution
from typing import List
class Solution:
def permute(self, nums: List[int]) -> List[List[int]]:
answer = []
def dfs(elements: List[int]) -> None:
if len(elements) == len(nums):
answer.append(elements[:])
return
for num in nums:
if num not in elements:
elements.append(num)
dfs(elements)
elements.pop()
for num in nums:
dfs([num])
return answer
Another Solution
from typing import List
class Solution:
def permute(self, nums: List[int]) -> List[List[int]]:
answer = []
visited = [False] * len(nums)
def dfs(index: int, elements: List[int]) -> None:
if len(elements) == len(nums):
answer.append(elements[:])
return
visited[index] = True
for j, n in enumerate(nums):
if not visited[j]:
elements.append(n)
dfs(j, elements)
elements.pop()
visited[index] = False
for i, num in enumerate(nums):
dfs(i, [num])
return answer
import itertools
from typing import List
class Solution:
def permute(self, nums: List[int]) -> List[List[int]]:
return itertools.permutations(nums)
Leave a comment