Notice
Recent Posts
Recent Comments
Link
일 | 월 | 화 | 수 | 목 | 금 | 토 |
---|---|---|---|---|---|---|
1 | 2 | |||||
3 | 4 | 5 | 6 | 7 | 8 | 9 |
10 | 11 | 12 | 13 | 14 | 15 | 16 |
17 | 18 | 19 | 20 | 21 | 22 | 23 |
24 | 25 | 26 | 27 | 28 | 29 | 30 |
31 |
Tags
- leetcode
- binary tree
- backtracking
- dfs
- 리트코드
- math
- Binary
- easy
- 문자열
- DP
- hash table
- Array
- string
- tree
- 중간
- 재귀
- recursive
- Depth-first Search
- Medium
- 쉬움
- two pointers
- sorting
- 미디움
- list
- HashTable
- linked list
- Python
- 이진트리
- matrix
- binary search
Archives
- Today
- Total
부부의 코딩 성장 일기
LeetCode 46(Permutations, Python) 본문
1. 문제 링크
Permutations - LeetCode
Can you solve this real interview question? Permutations - 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],
leetcode.com
2. 문제 설명
- [1,2,3] 이 주어지면 이 수들로 가능한 모둔 순열(중복X, 순서 구분O)을 반환하는 문제
- 예시) [1,2,3]이 주어지면 [[1,2,3], [1,3,2], [2,1,3], [2,3,1], [3,1,2], [3,2,1]]
3. 처음 풀이
- 전형적인 백트래킹
- [1,2,3]을 순회하며 temp = []에 원소가 이미 들어있지 않다면 추가.
- temp의 원소가 3개가 되면 답지 ans=[]에 temp 추가.
- temp에 대해 재귀함수 처리, 답이 아니라면 temp.pop()하여 이전부터 다시 탐색
class Solution:
def permute(self, nums: List[int]) -> List[List[int]]:
ans = []
def helper(temp, cur_nums):
if len(temp) == len(nums):
ans.append(temp[:])
return
else:
for num in nums:
if num not in temp:
temp.append(num)
helper(temp, nums)
temp.pop()
helper([],nums)
return ans
4. 다른 풀이
- 인수에 nums, path, res를 넣는다.
- nums의 i번째 요소를 path에 추가하고,
- nums에서 i번째 요소만 제외한 nums를 인수로 넣어 재귀를 때린다.
- nums는 하나씩 줄어들고 path는 하나씩 늘어난다.
- nums가 비어서 None이면 res에 현재 path를 추가한다.
class Solution:
def permute(self, nums: List[int]) -> List[List[int]]:
res = []
self.dfs(nums, [], res)
return res
def dfs(self, nums, path, res):
if not nums:
res.append(path)
#return # backtracking
for i in range(len(nums)):
self.dfs(nums[:i]+nums[i+1:], path+[nums[i]], res)
5. 배운 점
- 이제 백트래킹에 조금 익숙해질 수 있었다.
'Algorithm > LeetCode' 카테고리의 다른 글
LeetCode 48(Rotate Image, Python) (1) | 2024.01.05 |
---|---|
LeetCode 47(Permutations II, Python) (0) | 2024.01.04 |
LeetCode 45(Jump Game II, Python) (0) | 2024.01.02 |
LeetCode 43(Multiply Strings, Python) (0) | 2024.01.01 |
LeetCode 40(Combination Sum II, Python) (1) | 2023.12.31 |