46. Permutations
๐ต๏ธโ๏ธ Question
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]]
2:
Input: nums = [0,1]
Output: [[0,1],[1,0]]
3:
Input: nums = [1]
Output: [[1]]
๐ Constraints
- 1 <= nums.length <= 6
- -10 <= nums[i] <= 10
- All the integers of nums are unique.
๐โ๏ธ ํ์ด๋ณด์~
์๋ก ๋ค๋ฅธ ์ ์๋ฅผ ์ ๋ ฅ๋ฐ์ ๊ฐ๋ฅํ ๋ชจ๋ ์์ด์ ๋ฆฌํดํ๋ ๊ฐ๋จํ ์์ด ๋ฌธ์ ๋ค.
๋๊ฐ์ง์ ํ์ด๊ฐ ์กด์ฌํ๋ค.
version1 : DFS๋ฅผ ํ์ฉํ ์์ด ์์ฑ
๋ฐฑํธ๋ํน(backtracking)์ด๋? :
ํด๋ฅผ ์ฐพ๋ ๋์ค ํด๊ฐ ์๋์ด์ ๋งํ๋ฉด, ๋๋์๊ฐ์ ๋ค์ ํด๋ฅผ ์ฐพ์๊ฐ๋ ๊ธฐ๋ฒ์ ๋งํฉ๋๋ค.
์ต์ ํ ๋ฌธ์ ์ ๊ฒฐ์ ๋ฌธ์ ๋ฅผ ํธ๋ ๋ฐฉ๋ฒ์ด ๋ฉ๋๋ค.
์์ด์ด๋ ๋ชจ๋ ๊ฐ๋ฅํ ๊ฒฝ์ฐ๋ฅผ ๊ทธ๋ํ ํํ๋ก ๋์ดํ ๊ฒฐ๊ณผ์ด๋ค. -> ๊ทธ๋ํ๋ก ํํ ๊ฐ๋ฅํ๋ค.
# Runtime: 69 ms
# Memory Usage: 14.4 MB
class Solution:
def permute(self, nums: List[int]) -> List[List[int]]:
results = []
prev_elements = []
def dfs(elements) :
#๋ฆฌํ๋
ธ๋์ผ๋
if len(elements) == 0 :
results.append(prev_elements[:])
#์์ด ์์ฑ ์ฌ๊ท ํธ์ถ
for e in elements:
next_elements = elements[:]
next_elements.remove(e)
prev_elements.append(e)
# print("perv",prev_elements)
# print("next์ฌ๊ท๋๋ฌ๊ฐ์ฆ์",next_elements)
dfs(next_elements)
prev_elements.pop()
# print("**๋ฐฑํธ๋ํน",prev_elements)
dfs(nums)
return results
# input์ด [1,2,3] ๋ฉด ๋์ค๋ ์ถ๋ ฅ,,,
perv [1]
next์ฌ๊ท๋๋ฌ๊ฐ์ฆ์ [2, 3]
perv [1, 2]
next์ฌ๊ท๋๋ฌ๊ฐ์ฆ์ [3]
perv [1, 2, 3]
next์ฌ๊ท๋๋ฌ๊ฐ์ฆ์ []
**๋ฐฑํธ๋ํน [1, 2]
**๋ฐฑํธ๋ํน [1]
perv [1, 3]
next์ฌ๊ท๋๋ฌ๊ฐ์ฆ์ [2]
perv [1, 3, 2]
next์ฌ๊ท๋๋ฌ๊ฐ์ฆ์ []
**๋ฐฑํธ๋ํน [1, 3]
**๋ฐฑํธ๋ํน [1]
**๋ฐฑํธ๋ํน []
perv [2]
next์ฌ๊ท๋๋ฌ๊ฐ์ฆ์ [1, 3]
perv [2, 1]
next์ฌ๊ท๋๋ฌ๊ฐ์ฆ์ [3]
perv [2, 1, 3]
next์ฌ๊ท๋๋ฌ๊ฐ์ฆ์ []
**๋ฐฑํธ๋ํน [2, 1]
**๋ฐฑํธ๋ํน [2]
perv [2, 3]
next์ฌ๊ท๋๋ฌ๊ฐ์ฆ์ [1]
perv [2, 3, 1]
next์ฌ๊ท๋๋ฌ๊ฐ์ฆ์ []
**๋ฐฑํธ๋ํน [2, 3]
**๋ฐฑํธ๋ํน [2]
**๋ฐฑํธ๋ํน []
perv [3]
next์ฌ๊ท๋๋ฌ๊ฐ์ฆ์ [1, 2]
perv [3, 1]
next์ฌ๊ท๋๋ฌ๊ฐ์ฆ์ [2]
perv [3, 1, 2]
next์ฌ๊ท๋๋ฌ๊ฐ์ฆ์ []
**๋ฐฑํธ๋ํน [3, 1]
**๋ฐฑํธ๋ํน [3]
perv [3, 2]
next์ฌ๊ท๋๋ฌ๊ฐ์ฆ์ [1]
perv [3, 2, 1]
next์ฌ๊ท๋๋ฌ๊ฐ์ฆ์ []
**๋ฐฑํธ๋ํน [3, 2]
**๋ฐฑํธ๋ํน [3]
**๋ฐฑํธ๋ํน []
=========
perv [0]
next์ฌ๊ท๋๋ฌ๊ฐ์ฆ์ [1]
perv [0, 1]
next์ฌ๊ท๋๋ฌ๊ฐ์ฆ์ []
**๋ฐฑํธ๋ํน [0]
**๋ฐฑํธ๋ํน []
perv [1]
next์ฌ๊ท๋๋ฌ๊ฐ์ฆ์ [0]
perv [1, 0]
next์ฌ๊ท๋๋ฌ๊ฐ์ฆ์ []
**๋ฐฑํธ๋ํน [1]
**๋ฐฑํธ๋ํน []
version2. ํ์ด์ฌ์ itertools ๋ชจ๋์ ์ฌ์ฉํ๋ค.
itertools
๋ฐ๋ณต์ ์์ฑ์ ์ต์ ํ๋ ํจ์จ์ ์ธ ๊ธฐ๋ฅ๋ค์ ์ ๊ณต.
์ด๋ฏธ ์ ๊ตฌํ๋ ๋ผ์ด๋ธ๋ฌ๋ฆฌ๋ผ ๋ฒ๊ทธ ๋ฐ์ ๊ฐ๋ฅ์ฑ์ด ๋ฎ๊ณ ํจ์จ์ ์ผ๋ก ์ค๊ณ๋ C ๋ผ์ด๋ธ๋ฌ๋ฆฌ๋ผ ์๋๋ ๋น ๋ฆ
๐ ์ฌ์ฉํ ๋ ์ฃผ์์ผ๋ก "# ๊ตฌํ์ ํจ์จ์ฑ, ์ฑ๋ฅ์ ์ํด ์ฌ์ฉํ๋ค" ๋ผ๊ณ ๋ฌ์์ฃผ๋ฉด ์ต์ค~
permutation( ) ํจ์๊ฐ ํํ ๋ชจ์์ ๋ฐํํ๊ธฐ ๋๋ฌธ์ ๋ฆฌํธ์ฝ๋ ๋ฌธ์ ์์๋ ๋ฆฌ์คํธ๋ฅผ ๋ฐํํ๋๋ก ์๊ตฌํ๊ธฐ ๋๋ฌธ์ ๋ณํ์ฒ๋ฆฌ๋ฅผ ํด์ค์ผํ๋ค.
# Runtime: 28 ms
# Memory Usage: 14.3 MB
class Solution:
def permute(self, nums: List[int]) -> List[List[int]]:
import itertools
return list(map(list, itertools.permutations(nums)))