[LeetCode] 39. Combination Sum - 파이썬(Python)

2022. 5. 12. 14:41·Solving Algorithm Problem/LeetCode

문제 링크 : https://leetcode.com/problems/combination-sum/

 

Combination Sum - 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

유형 : 백트래킹(BackTracking)

문제 설명

중복되지 않는 정수들이 담긴 배열 candidates와 정수 target이 주어질 때, candidates에서 선택한 숫자들의 합이 target이 되는 조합을 찾아 모두 return 하는 문제이다. 이때, candidates의 숫자를 여러 번 사용하여 조합을 구성할 수 있다. 또한 [2,2,3]과 [3,2,2]는 동일한 조합으로 한 번만 return 해야 한다.

Example 1)
Input: candidates = [2,3,6,7], target = 7
Output: [[2,2,3],[7]]
Example 2)
Input: candidates = [2,3,5], target = 8
Output: [[2,2,2,2],[2,3,3],[3,5]]
Example 3)
Input: candidates = [2], target = 1
Output: []

제한사항

  • 1 <= candidates.length <= 30
  • 1 <= candidates[i] <= 200
  • candidates의 모든 숫자들은 중복되지 않는다.
  • 1 <= target <= 500

문제 풀이

성공 코드

from typing import List

class Solution:
    def combinationSum(self, candidates: List[int], target: int) -> List[List[int]]:
        self.candidates = candidates
        self.target = target
        self.combs = []
        
        self.bt(0, target, [])
        return self.combs
    
    def bt(self, prevIdx: int, targetSum: int, comb:List[int]):
        # exit conditions
        if targetSum == 0:
            self.combs.append(comb.copy())
            return
        elif targetSum < 0:
            return
        
        # process(candidates filtering)
        for idx in range(prevIdx, len(self.candidates)):
            num = self.candidates[idx]
            
            # recursion call
            comb.append(num)
            self.bt(idx, targetSum-num, comb)
            comb.pop()

시간복잡도 : T(n) <= n^(target/m + 1)

m은 후보들 중 가장 작은 수를 의미한다.

공간복잡도 : O(target/m)

m은 후보들 중 가장 작은 수를 의미한다.

저작자표시 (새창열림)
'Solving Algorithm Problem/LeetCode' 카테고리의 다른 글
  • [LeetCode] 746. Min Cost Climbing Stairs - 파이썬(Python)
  • [LeetCode] 70. Climbing Stairs - 파이썬(Python)
  • [LeetCode] 77. Combinations - 파이썬(Python)
  • [LeetCode] 46. Permutations - 파이썬(Python)
김행만
김행만
이모저모 다 적기
  • 김행만
    hyeinisfree
    김행만
  • 전체
    오늘
    어제
    • 분류 전체보기 (41)
      • AWS (0)
      • Network (6)
      • CICD (1)
      • Spring (0)
      • Ruby on Rails (0)
      • Java (12)
      • Python (1)
      • Computer Science (6)
        • Algorithm (2)
        • Data Structure (3)
        • Database (0)
        • Design Pattern (1)
      • Solving Algorithm Problem (12)
        • LeetCode (12)
        • Programmers (0)
      • 자격증 (1)
      • Tip (1)
      • Etc (1)
        • 도서, 강의 (1)
        • Talk (0)
  • 블로그 메뉴

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

    • GitHub
  • 공지사항

  • 인기 글

  • 태그

    cisco packet tracer
    java
    Packet Tracer
    CISCO
    java 필수 문법
    Network
  • 최근 댓글

  • 최근 글

  • hELLO· Designed By정상우.v4.10.3
김행만
[LeetCode] 39. Combination Sum - 파이썬(Python)
상단으로

티스토리툴바