https://leetcode.com/problems/subsets/
Subsets - 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 integer array nums of unique elements, return all possible subsets (the power set).
The solution set must not contain duplicate subsets. Return the solution in any order.
Example 1:
Input: nums = [1,2,3]
Output: [[],[1],[2],[1,2],[3],[1,3],[2,3],[1,2,3]]
Example 2:
Input: nums = [0]
Output: [[],[0]]
Constraints:
- 1 <= nums.length <= 10
- -10 <= nums[i] <= 10
- All the numbers of nums are unique.
깊이 우선 탐색 (DFS: Depth-First Search) 방법을 사용하여 문제를 풀 수 있다.
아래와 같이 탐색하는 알고리즘을 구현한다.

class Solution:
def subsets(self, nums):
result = []
def dfs(start, visited):
result.append(visited)
for idx in range(start, len(nums)):
dfs(idx + 1, visited + [nums[idx]])
dfs(0, [])
return result
'일하는 > Algorithm, Coding' 카테고리의 다른 글
[LeetCode][릿코드][Python][#17] Letter Combinations of a Phone Number (0) | 2021.11.16 |
---|---|
[LeetCode][릿코드][Python][#122] Best Time to Buy and Sell Stock II (0) | 2021.11.15 |
[LeetCode][릿코드][Python][#46] Permutations (0) | 2021.11.15 |
[BAE/<JOON>][백준][#1018] 체스판 다시 칠하기 (0) | 2020.09.23 |
[BAE/<JOON>][백준][#8913] 문자열 뽑기 (0) | 2020.08.28 |