문제
https://school.programmers.co.kr/learn/courses/30/lessons/43165
프로그래머스
코드 중심의 개발자 채용. 스택 기반의 포지션 매칭. 프로그래머스의 개발자 맞춤형 프로필을 등록하고, 나와 기술 궁합이 잘 맞는 기업들을 매칭 받으세요.
programmers.co.kr
package week6.baek.dfsbfs;
public class TargetNumber {
static int count = 0;
public static int solution(int[] numbers, int target) {
dfs(numbers,target, numbers[0], 1);
dfs(numbers, target, -numbers[0], 1);
return count;
}
public static void dfs(int[] numbers, int target, int result, int depth){
if(depth == numbers.length - 1){
if (result + numbers[depth] == target || result - numbers[depth] == target) {
count++;
return;
}
}
else {
dfs(numbers, target, result - numbers[depth], depth + 1);
dfs(numbers, target, result + numbers[depth], depth + 1);
}
}
public static void main(String[] args) {
int[] numbers = {1,1,1,1,1};
System.out.println(solution(numbers, 3));
}
}
이렇게 처음엔 했었는데 생각해보니 result=0, depth=0일 때로 시작하는게 더 깔끔하겠다
최종 코드
package week6.baek.dfsbfs;
public class TargetNumber {
static int count = 0;
public static int solution(int[] numbers, int target) {
dfs(numbers,target, 0,0);
return count;
}
public static void dfs(int[] numbers, int target, int result, int depth){
if(depth == numbers.length - 1){
if (result + numbers[depth] == target || result - numbers[depth] == target) {
count++;
return;
}
}
else {
dfs(numbers, target, result - numbers[depth], depth + 1);
dfs(numbers, target, result + numbers[depth], depth + 1);
}
}
public static void main(String[] args) {
int[] numbers = {1,1,1,1,1};
System.out.println(solution(numbers, 3));
}
}
'‡ CODING TEST STUDY ‡ > º 프로그래머스' 카테고리의 다른 글
[프로그래머스 | Java Lv.3] 단어 변환(dfs/bfs) (0) | 2024.06.14 |
---|---|
[프로그래머스 | Java Lv.2] [복습] 게임 맵 최단거리 (dfs/bfs) (1) | 2024.06.13 |
[프로그래머스 | Java Lv.2] [복습] 모음사전 (완전 탐색) (1) | 2024.06.11 |
[프로그래머스 | Java Lv.1] 모의고사 (완전 탐색) (0) | 2024.06.11 |
[프로그래머스 | Java Lv.2] [복습] H-index (정렬) (0) | 2024.06.11 |