[ 프로그래머스 ][ Java ] 타겟 넘버

chorok ☘️·2025년 7월 21일
0

코딩테스트

목록 보기
32/54
post-thumbnail

코딩테스트 연습 > 깊이/너비 우선 탐색(DFS/BFS) > 타겟 넘버

⚡ 문제 설명

n개의 음이 아닌 정수들이 있습니다. 이 정수들을 순서를 바꾸지 않고 적절히 더하거나 빼서 타겟 넘버를 만들려고 합니다. 예를 들어 [1, 1, 1, 1, 1]로 숫자 3을 만들려면 다음 다섯 방법을 쓸 수 있습니다.

-1+1+1+1+1 = 3
+1-1+1+1+1 = 3
+1+1-1+1+1 = 3
+1+1+1-1+1 = 3
+1+1+1+1-1 = 3

사용할 수 있는 숫자가 담긴 배열 numbers, 타겟 넘버 target이 매개변수로 주어질 때 숫자를 적절히 더하고 빼서 타겟 넘버를 만드는 방법의 수를 return 하도록 solution 함수를 작성해주세요.

⚡ 제한사항

  • 주어지는 숫자의 개수는 2개 이상 20개 이하입니다.
  • 각 숫자는 1 이상 50 이하인 자연수입니다.
  • 타겟 넘버는 1 이상 1000 이하인 자연수입니다.

⚡ 입출력 예

numberstargetresult
[1, 1, 1, 1, 1]35
[4, 1, 2, 1]42

⚡ 구현코드

class Solution {
    int count = 0;
    
    public int solution(int[] numbers, int target) {
        dfs(numbers, 0, target, 0);
        
        return count;
    }
    
    public void dfs(int[] numbers, int depth, int target, int temp){
        if(depth == numbers.length){
            if(target == temp) {
                count ++;
            }
            return;
        }
        
        int plus = temp + numbers[depth];
        int minus = temp - numbers[depth];
        
        dfs(numbers, depth+1, target, plus);
        dfs(numbers, depth+1, target, minus);
    }
}

⚡ 구현코드 해설

깊이 우선 탐색 (DFS) 알고리즘 이용
아래 그림을 먼저 이해하면 코드 구현이 조금 쉬워진다...!!!

  • int count: 전역 변수
  • int depth: 이진트리 깊이 (numbers 배열의 인덱스)
    마지막 노드까지 탐색하면 depth == numbers.length
  • int temp: 이전 노드까지의 합
  • dfs(int[] numbers, int depth, int target, int temp) : 깊이 우선 탐색을 위한 재귀 함수

참고: https://yeoeun-ji.tistory.com/144
profile
백엔드 개발자 chorok's velog

0개의 댓글