https://leetcode.com/problems/permutations/
Permutations - LeetCode
Level up your coding skills and quickly land a job. This is the best place to expand your knowledge and get prepared for your next interview.
leetcode.com
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] <= 10
- All the integers of nums are unique.
깊이 우선 탐색 (DFS: Depth-First Search) 방법을 사용하여 문제를 풀 수 있다.
아래와 같이 탐색하는 알고리즘을 구현한다.
class Solution:
def permute(self, nums):
result , visited = [], []
def dfs(nums):
if len(nums) == 0:
result.append(visited[:])
for num in nums:
next = nums[:]
next.remove(num)
visited.append(num)
dfs(next)
visited.pop()
dfs(nums)
return result
'일하는 > Algorithm, Coding' 카테고리의 다른 글
[LeetCode][릿코드][Python][#122] Best Time to Buy and Sell Stock II (0) | 2021.11.15 |
---|---|
[LeetCode][릿코드][Python][#78] Subsets (0) | 2021.11.15 |
[BAE/<JOON>][백준][#1018] 체스판 다시 칠하기 (0) | 2020.09.23 |
[BAE/<JOON>][백준][#8913] 문자열 뽑기 (0) | 2020.08.28 |
[BAE/<JOON>][백준][#1003] 피보나치 함수 (0) | 2019.09.19 |