Problem : 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
Approach
BFS나 DFS로 탐색하여 target number에 몇번 도착하는지를 계산하면 된다.
보통 DFS/BFS 는 목적지까지의 최소비용을 구하는데에 사용하지만, 이 문제에서는 최소비용이 아니라 몇번 도착하는지를 구하면 된다.
Code
public class TargetNumber {
static int count = 0;
public static void main(String[] args) {
int[] numbers = {1, 1, 1, 1, 1};
int target = 3;
TargetNumber t = new TargetNumber();
System.out.println(t.solution(numbers, target));
}
public int solution(int[] numbers, int target) {
dfs(0, 0, target, numbers);
return count;
}
static void dfs(int x, int index, int target, int[] numbers) {
if (index == numbers.length) {
if (x == target) {
count += 1;
}
return;
}
dfs(x + numbers[index], index + 1, target, numbers);
dfs(x - numbers[index], index + 1, target, numbers);
}
}
'Algorithm > Programmers' 카테고리의 다른 글
[java] 프로그래머스 (가장 큰 정사각형 찾기) Level 2 (0) | 2021.01.09 |
---|---|
[java] 프로그래머스 (쿼드압축 후 개수 세기) Level 2 (0) | 2021.01.09 |
[java] 프로그래머스 (카펫) Level 2 (0) | 2021.01.08 |
[java] 프로그래머스 (구명보트) Level 2 (0) | 2021.01.06 |
[java] 프로그래머스 (위장) Level 2 (0) | 2021.01.04 |