Skip to content

Commit 2670dab

Browse files
committed
feat: Add 타켓넘버 DFS 풀이
1 parent 14a7143 commit 2670dab

File tree

1 file changed

+29
-0
lines changed

1 file changed

+29
-0
lines changed
Lines changed: 29 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,29 @@
1+
package com.hyeonah.javalabs.algorithm.programmers.dfsandbfs;
2+
3+
/**
4+
* DFS,BFS > 타겟넘버
5+
* https://programmers.co.kr/learn/courses/30/lessons/43165
6+
*
7+
* 주어진 numbers에 +,- 연산 하는 경우 모두 탐색
8+
*
9+
*/
10+
public class Solution43165 {
11+
public static void main(final String[] args) {
12+
final int[] numbers = {1, 1, 1, 1, 1};
13+
final int target = 3;
14+
System.out.println(new Solution43165().solution(numbers, target)); // 5
15+
}
16+
17+
// DFS, 재귀 이용
18+
public int solution(final int[] numbers, final int target) {
19+
return dfs(numbers, 0, 0, target);
20+
}
21+
22+
private int dfs(final int[] numbers, final int index, final int sum, final int target) {
23+
if(index == numbers.length) {
24+
return sum == target ? 1 : 0;
25+
}
26+
return dfs(numbers, index + 1, sum + numbers[index], target)
27+
+ dfs(numbers, index + 1, sum - numbers[index], target);
28+
}
29+
}

0 commit comments

Comments
 (0)