- 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