Algorithm/프로그래머스

프로그래머스 | 타겟 넘버(DFS)

jihyun03 2020. 8. 28. 19:13

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

 

📖 문제 풀이

 

DFS에서는 점화식종료조건을 찾는 것이 가장 중요하다.

 

 

📖 소스 코드

public class 타겟넘버 {
	public static void main(String[] args) {
		int[] numbers = {1,1,1,1};
		int target =  3;

		System.out.println(solution(numbers, target));
	}

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

	public int DFS(int[] numbers, int target, int index, int num) {
		if(index == numbers.length) {
			return num == target ? 1 : 0;
		} else {
			return DFS(numbers, target, index + 1, num + numbers[index])
					+ DFS(numbers, target, index + 1, num - numbers[index]);
		}
	}
	
}

 

참고 :  https://lkhlkh23.tistory.com/74