반응형
LeetCode 문제 해석 및 풀이 방법
문제 46. Permutations(순열)
난이도 : 중간🟡 바로가기
문제 설명
영문
Given an array nums of distinct integers, return all the possible permutations. You can return the answer in any order.
한글
고유한 정수의 배열 nums 주어지면 가능한 모든 순열을 반환합니다. 어떤 순서 로든 답변을 반환할 수 있습니다.
제한조건
- 1 <= nums.length <= 6
- -10 <= nums[i] <= 10
- All the integers of nums are unique.
입출력 예
입력 | 출력 |
nums = [1,2,3] | [[1,2,3],[1,3,2],[2,1,3],[2,3,1],[3,1,2],[3,2,1]] |
nums = [0,1] | [[0,1],[1,0]] |
nums = [1] | [[1]] |
해답 및 해설
파이썬 (Python)
class Solution:
def permute(self, nums: List[int]) -> List[List[int]]:
n = len(nums)
answer = []
def swapHelper(arr, depth):
if depth == n:
answer.append(arr)
return
for i in range(depth, n):
arr[depth], arr[i] = arr[i], arr[depth]
swapHelper(arr.copy(), depth + 1)
arr[depth], arr[i] = arr[i], arr[depth]
swapHelper(nums, 0)
return answer
원소를 스왑해가며 정하는 방식
https://programming4myself.tistory.com/94
🧮 순열 알고리즘 직접 구현!
순열과 중복순열 알고리즘을 파이썬으로 구현하기 순열이란? 원소들을 순서에 따라 나열하는 것 n개의 원소에서 r개를 나열한다 하면 그 가짓수는 n!/(n-r)! 중복해서 원소를 뽑으면 n^r 전체 순열
programming4myself.tistory.com
이 외의 순열을 푸는 방법은 해당 게시글에 올려두었다.
반응형
'🖥️ 문제 풀이 > 리트코드(Leetcode)' 카테고리의 다른 글
[LeetCode 해석 및 풀이] 90. Subsets II(하위 집합 II) (0) | 2024.08.07 |
---|---|
[LeetCode 해석 및 풀이] 39. Combination Sum(조합 합) (0) | 2024.08.06 |
[LeetCode 해석 및 풀이] 78. Subsets(하위 집합) (0) | 2024.07.28 |
[LeetCode 해석 및 풀이] 105. Construct Binary Tree from Preorder and Inorder Traversal(선위, 중위 순회에서 이진 트리 구성) (0) | 2024.07.28 |
[LeetCode 해석 및 풀이] 230. Kth Smallest Element in a BST(BST의 K번째로 작은 요소) (0) | 2024.07.28 |
댓글