일하는/Algorithm, Coding

[LeetCode][릿코드][Python][#78] Subsets

김논리 2021. 11. 15. 13:22

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