프로그래머스 43165. 타겟 넘버

2025. 1. 15. 17:10·프로그래머스

https://school.programmers.co.kr/learn/courses/30/lessons/43165

 

프로그래머스

SW개발자를 위한 평가, 교육, 채용까지 Total Solution을 제공하는 개발자 성장을 위한 베이스캠프

programmers.co.kr

1. dfs 풀이

def solution(numbers, target):
    ans = 0  # 타겟 넘버를 만드는 방법의 수

    def dfs(depth, current_sum):
        nonlocal ans
        # 모든 숫자를 사용한 경우
        if depth == len(numbers):
            if current_sum == target:
                ans += 1
            return
        
        # 현재 숫자를 더하거나 빼는 두 가지 선택
        dfs(depth + 1, current_sum + numbers[idx])
        dfs(depth + 1, current_sum - numbers[idx])
    
    # DFS 탐색 시작
    dfs(0, 0)
    return ans

2. product 풀이

from itertools import product

def solution(numbers, target):
    l = [(x, -x) for x in numbers]
    s = list(map(sum, product(*l))) # product에 repeat 값 안넣어줌=기본값=1=자기자신 제외
    return s.count(target)

https://velog.io/@davkim1030/Python-%EC%88%9C%EC%97%B4-%EC%A1%B0%ED%95%A9-product-itertools

 

Python 순열, 조합, product - itertools

파이썬으로 코딩할 때, 종종 순열, 조합, product를 구현하거나 사용해야 할 때가 있다. 이럴 때 힘들게 구현하지 말고 파이썬에서 만들어둔 표준 라이브러리인 itertools를 사용해보자조합을 표현할

velog.io

combinations 조합, 중복x

 - itertools.combinations(iterable, r)

permutations 순열, 중복o

 - itertools.permutations(iterable, r)

product 두 개 이상의 모든 리스트들의 조합

 - itertools.product(*iterables, repeat=1)

저작자표시 (새창열림)

'프로그래머스' 카테고리의 다른 글

프로그래머스 43163. 단어 변환  (0) 2025.01.17
프로그래머스 1844. 게임 맵 최단거리  (0) 2025.01.17
프로그래머스 84512. 모음사전  (0) 2025.01.15
프로그래머스 42839. 소수 찾기  (0) 2025.01.14
프로그래머스 42579. 베스트앨범  (0) 2025.01.14
'프로그래머스' 카테고리의 다른 글
  • 프로그래머스 43163. 단어 변환
  • 프로그래머스 1844. 게임 맵 최단거리
  • 프로그래머스 84512. 모음사전
  • 프로그래머스 42839. 소수 찾기
버그잡는고양이발
버그잡는고양이발
주니어 개발자입니다!
  • 버그잡는고양이발
    지극히평범한개발블로그
    버그잡는고양이발
  • 전체
    오늘
    어제
    • 분류 전체보기 (381)
      • React (16)
      • Next.js (5)
      • Javascript (5)
      • Typescript (4)
      • Node.js (2)
      • Cs (16)
      • 트러블 슈팅 (5)
      • Html (1)
      • Css (3)
      • Django (0)
      • vue (0)
      • Java (1)
      • Python (0)
      • 독서 (1)
      • 기타 (3)
      • 백준 (192)
      • swea (31)
      • 프로그래머스 (30)
      • 이코테 (4)
      • 99클럽 코테 스터디 (30)
      • ssafy (31)
      • IT기사 (1)
  • 블로그 메뉴

    • 홈
    • 태그
  • 인기 글

  • 태그

    Til
    99클럽
    코딩테스트준비
    항해99
    개발자취업
  • 최근 댓글

  • 최근 글

  • hELLO· Designed By정상우.v4.10.3
버그잡는고양이발
프로그래머스 43165. 타겟 넘버
상단으로

티스토리툴바