Notice
Recent Posts
Recent Comments
Link
일 | 월 | 화 | 수 | 목 | 금 | 토 |
---|---|---|---|---|---|---|
1 | 2 | 3 | 4 | |||
5 | 6 | 7 | 8 | 9 | 10 | 11 |
12 | 13 | 14 | 15 | 16 | 17 | 18 |
19 | 20 | 21 | 22 | 23 | 24 | 25 |
26 | 27 | 28 | 29 | 30 | 31 |
Tags
- Java
- 이중우선순위큐 자바
- DP
- 백트래킹
- SQL
- 백준
- CJ DBASE&
- 위상정렬
- DBASE&
- 면접 필수 질문
- oracle ansi
- DFS
- oracle ansi sql
- ansi sql 단점
- 프로그래머스 이중우선순위큐
- BFS
- Spring Boot
- ansi sql 장점
- 프로그래머스 이중우선순위큐 자바
- 이중우선순위큐 java
- 프로그래머스
- IT 면접 준비
- 개발자 면접 준비
- 이분탐색
- 그리디
- 프로그래머스 이중우선순위큐 java
- JPA
- Gradle
- 디베이스앤 인턴 후기
- 디베이스앤
Archives
- Today
- Total
쉬운 프로그래밍
[알고리즘] 프로그래머스 - 타겟 넘버 본문
programmers.co.kr/learn/courses/30/lessons/43165
import java.util.*;
class Solution {
public int solution(int[] numbers, int target) {
return dfs(numbers, target, 0, 0);
}
public int dfs(int[] numbers, int target, int depth, int value) {
if (depth == numbers.length) {
if (value == target) {
return 1;
}
return 0;
}
int plus = dfs(numbers, target, depth + 1, value + numbers[depth]);
int minus = dfs(numbers, target, depth + 1, value - numbers[depth]);
return plus + minus;
}
}
dfs를 통해 문제를 해결하였다.
재귀함수의 depth가 numbers.length가 된다면 sum이 target과 동일한지 검색한다.
동일하다면 1을 반환하여 카운트를 하나 높여준다.
위와 같이 두개의 재귀함수를 돌리게 되면 아래와 같은 탐색과정이 나온다.
첫번째 재귀함수 빨간 부분의 트리를 만들고,
그 이후로 return라인의 오른쪽 재귀함수가 호출되어 현재 인덱스값을 이전 인덱스값에서 빼주는 과정을 수행한다.
# BFS 풀이 추가
import java.util.*;
class Solution {
public int solution(int[] numbers, int target) {
// return dfs(numbers, target, 0, 0);
return bfs(numbers, target);
}
public int bfs(int[] numbers, int target) {
int plus = numbers[0];
int minus = numbers[0] * -1;
int count = 0;
Queue<Location> queue = new LinkedList<>();
queue.add(new Location(plus, 0));
queue.add(new Location(minus, 0));
while (!queue.isEmpty()) {
Location current = queue.poll();
if (current.x == target && current.y == numbers.length - 1) {
count++;
}
if (current.y < numbers.length - 1) {
Location nextPlus = new Location(current.x + numbers[current.y + 1], current.y + 1);
Location nextMinus = new Location(current.x - numbers[current.y + 1], current.y + 1);
queue.add(nextPlus);
queue.add(nextMinus);
}
}
return count;
}
class Location {
int x;
int y;
public Location(int x, int y) {
this.x = x;
this.y = y;
}
}
}
BFS 풀이는 DFS보다 다소 복잡하다.
처음 시작할 때, 큐 안에 양수로 시작하는 숫자와 음수로 시작하는 숫자를 모두 넣어 풀이를 진행한다.
입력으로 주어진 모든 숫자를 다 쓸 때까지, 다음 숫자를 더한값과 뺀값을 모두 큐에 집어넣는다.
그렇게 하고 큐에서 빠지는 값들이 target과 일치하며, 그 값은 모든 숫자를 다 써서 나왔다는 것이 증명되면
count를 1씩 더해준 후 마무리한다.
'알고리즘 > DFS, BFS' 카테고리의 다른 글
[알고리즘] 백준 2146 다리만들기 (0) | 2021.03.03 |
---|---|
[알고리즘] 프로그래머스 - 네트워크 (0) | 2021.01.25 |
[알고리즘] 백준 4179 불 (0) | 2021.01.24 |
[알고리즘] 백준 2583 영역 구하기 (0) | 2021.01.23 |
[알고리즘] 백준 7569 토마토 (3) | 2021.01.05 |
Comments