less than 1 minute read



문제 풀이




작성 코드


1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
import java.util.*;

class Solution {
    // 타겟이 될 경우를 카운트할 변수
    static int answer = 0;
    public int solution(int[] numbers, int target) {
        // DFS 재귀함수 호출
        DFS(numbers, target, 0, 0);
        return answer;
    }
    // 배열의 수를 더하거나 빼가면서 타겟 넘버가 되는지를 탐색할 재귀함수
    static void DFS(int[] numbers, int target, int sum, int cnt) {
        // 배열의 마지막 노드까지 탐색했을 때
        if(cnt == numbers.length) {
            // sum 변수가 타겟넘버와 같다면 answer를 1 증가시킨다.
            if(target == sum) {
                answer++;
            }
        } else {
            // 마지막 노드까지 탐색하지 않았다면 더하거나 뺄셈할 재귀함수 호출
            DFS(numbers, target, sum+numbers[cnt], cnt+1);
            DFS(numbers, target, sum-numbers[cnt], cnt+1);
        }
    }

    public static void main(String[] args) {
        Solution sol = new Solution();
        
        int[] numbers = new int[]{1,1,1,1,1};
        int target = 3;

        sol.solution(numbers, target);
    }
}

회고



출처


  • 해당 문제의 저작권은 문제를 만든이에게 있으며 자세한 내용은 문제 링크에서 참조바랍니다.