my study.

Coding Test/Programmers

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

fftl 2025. 1. 28. 13:57

- 문제

 

프로그래머스

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

programmers.co.kr

- 풀이

class Solution {
    
    //static으로 사용하면 편할 것으로 생각된 값들을
    //선언하여줍니다.
    static int result, len, tg;
    static int[] nums;
    
    public int solution(int[] numbers, int target) {
        //static에 해당하는 변수들을 채워 전역적으로 사용하도록 만듭니다.
        result = 0;
        nums = numbers;
        tg = target;
        len = numbers.length;
        
        //dfs를 이용해 +, -의 경우에 대한 값들을 확인합니다.
        dfs(0, 0);

        //결과 값 result를 반환합니다.
        return result;
    }
    
    //핵심이되는 dfs 함수입니다.
    static void dfs(int now, int idx){
        
        //만약 이번 idx가 주어진 numbers의 범위를 넘어섰을 경우
        //이번 계산은 끝난 것이므로 target과 비교해 준 뒤 result를 update 해줍니다.
        if(idx==len){
            if(now==tg) result++;
            
        //아직 계산이 끝나지 않았을 경우입니다.
        } else {
            
            //이번 순서의 수를 더하거나, 빼는 경우 모두의 dfs를 확인합니다.
            //idx는 동일하게 증가시켜줍니다.
            dfs(now+nums[idx], idx+1);
            dfs(now-nums[idx], idx+1);
        }
        
    }
}