깊이/너비 우선 탐색(DFS/BFS) _타겟 넘버

H802·2025년 1월 23일

코딩 테스트

목록 보기
11/11

📘 문제

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 함수를 작성해주세요.

입출력 예

numberstargetreturn
[1, 1, 1, 1, 1]35
[4, 1, 2, 1]42
[1, 2, 3, 4]71

📑 풀이

class Solution {
    public int answer = 0; // 타겟 넘버를 만드는 방법의 수
    
    public int solution(int[] numbers, int target) {
        dfs(numbers, 0 , 0 , target);
        return answer;
    }
    
    // 깊이 우선 탐색
    public void dfs(int[] numbers, int index, int currentSum, int target){
        if(index == numbers.length){
            if(currentSum == target){
                answer++;
            }
            return; // 종료
        }
        
        // 현재 숫자 더하기
        dfs(numbers, index+1, currentSum+numbers[index], target);
        // 현재 숫자 빼기
        dfs(numbers, index+1, currentSum-numbers[index], target);
    }
}

👀 문제 출처

profile
배운 내용 정리하기 위해 쓰는 블로그

0개의 댓글