[LeetCode]Subsets

2023. 5. 29. 20:08·SW개발/코딩테스트

https://leetcode.com/problems/subsets/

 

Subsets - LeetCode

Can you solve this real interview question? Subsets - 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: n

leetcode.com

 

문제 분석

주어진 숫자배열을 가지고 가능한 모든 부분집합을 구하는 문제입니다. 순서는 상관 없습니다.

 

처음 시도한 답안

class Solution:
    def subsets(self, nums: List[int]) -> List[List[int]]:
        answer = []

        def dfs(answer, nums, path):
            answer.append(path[:])

            for idx, num in enumerate(nums):
                path.append(num)
                dfs(answer, nums[idx+1:], path)
                path.pop()

        dfs(answer, nums, [])

        return answer

접근 방법

  1. dfs를 이용해 Subsets을 구합니다.
  2. answer에 path를 기록합니다.
  3. 파라미터로 전달받은 nums 요소를 순회합니다.
  4. path에 num을 등록합니다.
  5. dfs를 재귀적으로 실행합니다. nums의 요소는 idx+1로 슬라이싱 합니다.
  6. path에 등록한 num을 제거합니다.

기본적인 DFS 알고리즘을 활용해 Subsets을 구할 수 있습니다. 탐색하는 경로는 다음과 같습니다.

# path 경로
[]
[1]
[1, 2]
[1, 2, 3]
[1, 3]
[2]
[2, 3]
[3]

따라서 이 경로들을 모두 answer에 넣어주면 됩니다.

 

728x90

'SW개발 > 코딩테스트' 카테고리의 다른 글

[LeetCode]Validate Binary Search Tree  (0) 2023.05.31
[LeetCode]Word Search  (0) 2023.05.30
[LeetCode]Sort Colors  (0) 2023.05.28
[LeetCode]Search a 2D Matrix  (0) 2023.05.27
[LeetCode]Set Matrix Zeroes  (0) 2023.05.26
'SW개발/코딩테스트' 카테고리의 다른 글
  • [LeetCode]Validate Binary Search Tree
  • [LeetCode]Word Search
  • [LeetCode]Sort Colors
  • [LeetCode]Search a 2D Matrix
Leffe_pt
Leffe_pt
개발자로서 성장하면서 배워온 지식과 경험을 공유하는 공간입니다.
  • Leffe_pt
    Leffe's tistory
    Leffe_pt
  • 전체
    오늘
    어제
    • 분류 전체보기 (309)
      • SW개발 (305)
        • 코딩테스트 (172)
        • 개발이야기 (23)
        • IT 용어 (17)
        • Python (22)
        • Django (46)
        • Flask (2)
        • Database (3)
        • SQLAlchemy (0)
        • Javascript (5)
        • Linux, Unix (3)
        • JAVA (2)
        • Spring (10)
      • 회고 (4)
      • 사진 (0)
  • 블로그 메뉴

    • 홈
    • 태그
    • 방명록
  • 링크

  • 공지사항

  • 인기 글

  • 태그

    음식
    g
    어플리케이션
    라이프 스타일
    트리 #AVL #알고리즘 #자료구조
    django
    오픈소스
    배공파용
    컨트리뷰터
    배달비 공유
    플레이스토어
    배달
    Contributor
  • 최근 댓글

  • 최근 글

  • hELLO· Designed By정상우.v4.10.3
Leffe_pt
[LeetCode]Subsets
상단으로

티스토리툴바