[PG_LV2] 타겟 넘버

Pavel_Dmr·2022년 7월 18일

Programmers LEVEL 2

목록 보기
4/5

int 배열 numbers과 int 자료형 target이 있고, numbers내에 정수을 양수,음수로 조합하여 전부 합했을 때, target의 값이 같은 경우의 수가 몇개 인지 도출하는 문제이다.

🧈 나의 풀이

package PG_Lv_2.타겟넘버_008;

public class Solution
{
	// 전역변수 최종답안 answer
    int answer = 0;

	//테스트 메서드
    public static void main(String[] arg)
    {
        Solution solution = new Solution();

        int[] arr =
        { 4, 1, 2, 1 };
        int test = 4;
        System.out.println(solution.solution(arr, test));

    }

    public int solution(int[] numbers, int target)
    {

        DFS_Search(numbers, target, 0, 0);
        return answer;
    }

    private void DFS_Search(int[] numbers, int target, int sum, int try_time)
    {
   		 //합이 target과 같고, 시도한 횟수가 배열 숫자들의 크기와 같으면
        if (sum == target && try_time == numbers.length)
        {
            ++answer; // 조건에 부합하니 경우의 수을 늘린다.
            return; // 메서드 탈출
        }
        //시도한 횟수가 배열 숫자들의 크기와 같으면( == 숫자들을 전부 다 합했으면)
        else if (try_time == numbers.length)
        {
            return; // 메서드 탈출
        }

		//양수을 더했을때의 경우의 수
        DFS_Search(numbers, target, sum + numbers[try_time], try_time + 1);
     	//음수을 더했을때의 경우의 수
        DFS_Search(numbers, target, sum - numbers[try_time], try_time + 1);
    }

}

profile
노는게 좋아

0개의 댓글