https://www.acmicpc.net/problem/1182
접근 :
- 각 숫자를 더하는 경우와 더하지 않는 경우로 분리 해서 DFS 시행
- DFS 마지막에 목표값과 동일한 경우 result + 1
코드구현 :
import java.io.*;
public class Main {
private static int n;
private static int target;
private static int[] nums;
private static int result;
static void input() throws IOException{
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
String[] inputs = br.readLine().split(" ");
n = Integer.parseInt(inputs[0]);
target = Integer.parseInt(inputs[1]);
nums = new int[n+1];
inputs = br.readLine().split(" ");
for(int i = 1 ; i <= n ; i++) nums[i] = Integer.parseInt(inputs[i-1]);
br.close();
}
static void recFunc(int now, int temp_res){
if(temp_res + nums[now] == target) result++;
if(now == n) return;
recFunc(now + 1, temp_res + nums[now]);
recFunc(now + 1, temp_res);
}
public static void main(String[] args) throws IOException{
input();
recFunc(1, 0);
System.out.println(result);
}
}
'JAVA > Coding Test' 카테고리의 다른 글
[JAVA] 백준 1138 한 줄로 서기 (0) | 2024.05.20 |
---|---|
[JAVA] 백준 1759 암호 만들기_브루트포스 (0) | 2024.05.20 |
[JAVA] 백준 14888 연산자 끼워넣기_브루트포스 (0) | 2024.05.18 |
[JAVA] 백준 4673 셀프 넘버_브루트포스 (0) | 2024.02.04 |
[JAVA] 백준 7785 회사에 있는 사람_집합과 맵 (0) | 2023.04.17 |