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] <= 10nums are unique.
class Solution:
def permute(self, nums: List[int]) -> List[List[int]]:
result = itertools.permutations(nums, len(nums))
return result
위의 문제는 중복되지 않는 모든 수열을 찾는 문제로서, Python의 내장모듈 itertools.permutations 메소드를 이용하여 쉽게 모든 순열의 리스트를 찾을 수 있다.
class Solution:
def permute(self, nums: List[int]) -> List[List[int]]:
# 모든순열의 리스트 초기화
result = []
# 각 순열 리스트 초기화
prev_lst = []
# dfs 탐색
def dfs(elements):
# base case
if len(elements) == 0:
# prev_list를 append하면 prev_list의 결과값을 참조하는 것이 아니라
# prev_list에 대한 참조가 추가된다.
# 그래서 prev_list를 카피떠서 추가한다.
result.append(prev_lst[:])
return
for e in elements:
next_elements = elements[:]
next_elements.remove(e)
prev_lst.append(e)
dfs(next_elements)
prev_lst.pop()
dfs(nums)
return result
안녕하세요! 혹시 리트코드를 쓰시는 이유가 있을까요? 영어라서 쓸까말까 고민중인데 쓸만한가 해서요