728x90
(↓isChanged 패러미터 생략함)
isChanged를 지우기 위해서는 sum이 0일때 공집합의 경우를 1회 빼줘야함;;...
풀이 안 봤으면 isChanged끼고 해야 했을듯
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
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
|
import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
public class Main {
private static BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
private static BufferedWriter bw = new BufferedWriter(new OutputStreamWriter(System.out));
private static int[] num;
private static int S;
private static int res;
private static void bt(int tot, int pos) {
if(pos == num.length) {
if(tot==S)
res++;
return;
}
bt(tot+num[pos] ,pos+1);
bt(tot, pos+1);
}
public static void main(String[] args) throws IOException{
String[] str = br.readLine().split(" ");
int N = stoi(str[0]);
S = stoi(str[1]);
res = 0;
num = new int[N];
str = br.readLine().split(" ");
for (int i=0; i<N; i++)
num[i] = stoi(str[i]);
bt(0 , 0);
res = (S==0)? --res : res;
bw.write(String.valueOf(res));
bw.flush();
bw.close();
}
private static int stoi(String input) {
return Integer.parseInt(input);
}
}
|
cs |
(↓처음에 푼 것)
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
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
|
import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
public class Main {
private static BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
private static BufferedWriter bw = new BufferedWriter(new OutputStreamWriter(System.out));
private static int[] num;
private static int S;
private static int res;
private static void bt(int tot, int pos, boolean isChanged) {
if(tot == S && isChanged)
res++;
if(pos == num.length)
return;
bt(tot+num[pos] ,pos+1,true);
bt(tot, pos+1, false);
}
public static void main(String[] args) throws IOException{
String[] str = br.readLine().split(" ");
int N = stoi(str[0]);
S = stoi(str[1]);
res = 0;
num = new int[N];
str = br.readLine().split(" ");
for (int i=0; i<N; i++)
num[i] = stoi(str[i]);
bt(0 , 0, false);
bw.write(String.valueOf(res));
bw.flush();
bw.close();
}
private static int stoi(String input) {
return Integer.parseInt(input);
}
}
|
cs |
'알고리즘 풀이 > 백준' 카테고리의 다른 글
[백준][Java] 11866번 요세푸스 문제 0 (구현) (0) | 2021.10.04 |
---|---|
[백준][Java] 1759번 암호 만들기 (백트래킹, 브루트포스) (0) | 2021.10.04 |
[백준][Java] 2448번 별 찍기 - 11 (분할정복, 재귀) #2 (0) | 2021.10.03 |
★ [백준][Java] 2447번 별 찍기 - 10 (분할정복, 재귀) #2 (0) | 2021.10.02 |
★ [백준][Java] 1074번 Z (분할정복, 재귀) (0) | 2021.10.02 |