본문 바로가기
알고리즘/프로그래머스

프로그래머스 LV2. 타겟 넘버 (자바)

by reumiii 2021. 9. 29.

🍀 문제

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

 

입출력 예

numbers target return
[1, 1, 1, 1, 1] 3 5

 

https://programmers.co.kr/learn/courses/30/lessons/43165

 

코딩테스트 연습 - 타겟 넘버

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

programmers.co.kr

 

나의 코드 😊

class Solution {
    static int count = 0;

    public int solution(int[] numbers, int target) {
        targetCnt(numbers, 0, 0, target);
        return count;
    }

    public void targetCnt(int[] numbers, int index, int sum, int target) {
        if (index == numbers.length) {
        	//마지막 numbers까지 조합했다면
            if (sum == target) { //합계가 타겟 넘버와 같은지 보아 count 1 추가
                count++;
            }
        } else {
            targetCnt(numbers, index + 1, sum + numbers[index], target);// +조합
            targetCnt(numbers, index + 1, sum - numbers[index], target);// -조합
        }
    }
}

 

 

✌ 두 번째 풀었을때

class Solution {
    public int solution(int[] numbers, int target) {
		return targetCnt(numbers, target, 0, 0);
	}

	public int targetCnt(int[] numbers, int target, int index, int sum) {
		if (index >= numbers.length) {
			if (sum == target) {
				return 1;
			} else {
				return 0;
			}
		}

		return targetCnt(numbers, target, index + 1, sum + numbers[index])
				+ targetCnt(numbers, target, index + 1, sum - numbers[index]);
	}
}

 

방법의 수를 구하는 count 변수를 따로 두지 않고

마지막 요소까지 확인했을때 target과 sum이 같으면 1을 리턴, 다르면 0을 리턴해서

리턴된 값들을 더하여 방법의 수를 구했다.

 

댓글