알고리즘/프로그래머스
[프로그래머스] 타겟 넘버-JAVA
jimkwon
2022. 3. 9. 18:49
반응형
문제 링크
https://programmers.co.kr/learn/courses/30/lessons/43165
코딩테스트 연습 - 타겟 넘버
n개의 음이 아닌 정수들이 있습니다. 이 정수들을 순서를 바꾸지 않고 적절히 더하거나 빼서 타겟 넘버를 만들려고 합니다. 예를 들어 [1, 1, 1, 1, 1]로 숫자 3을 만들려면 다음 다섯 방법을 쓸 수
programmers.co.kr
흔한 dfs문제이다.
재귀를 사용하여 numbers의 숫자를 더하거나 빼는 모든 경우의 수를 다 거쳐본다.
마지막 numbers 원소까지 연산이 끝났을 때, 총 연산값이 target과 일치하면 answer + 1
class Solution {
int answer = 0;
public void dfs(int[] num, int total, int depth, int target) {
if (depth == 0) {
if (total == target)
answer++;
return;
}
dfs(num, total + num[num.length - depth], depth - 1, target);
dfs(num, total - num[num.length - depth], depth - 1, target);
}
public int solution(int[] numbers, int target) {
dfs(numbers, 0, numbers.length, target);
return answer;
}
}
사실상 모든 연산의 종류를 다 돌아보는 완전탐색에 가깝다.