BOJ_S2_1182
๐ [S2_1182] ๋ถ๋ถ์์ด์ ํฉ
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.StringTokenizer;
public class Main {
static StringTokenizer st;
static int N,S;
// ํฉ
static int sum = 0;
// ์นด์ดํธ ( ๊ฒฐ๊ณผ๊ฐ )
static int res = 0;
static int[] arr;
static boolean[] isCheck;
public static void main(String[] args) throws IOException{
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
StringBuilder sb = new StringBuilder();
st = new StringTokenizer(br.readLine(), " ");
N = Integer.parseInt(st.nextToken());
S = Integer.parseInt(st.nextToken());
arr = new int[N];
isCheck = new boolean[N];
// ๋ฐฐ์ด ์
๋ ฅ
st = new StringTokenizer(br.readLine(), " ");
for(int i=0; i<N; i++) {
arr[i] = Integer.parseInt(st.nextToken());
}
dfs(0);
// ๋ค false์ธ ๊ฒฝ์ฐ
if(S == 0) {
res--;
}
sb.append(res);
System.out.println(sb);
}
static void dfs(int current) {
if(current == N) {
for(int i=0; i<N; i++) {
if(isCheck[i]) {
sum += arr[i];
}
else {
continue;
}
}
if(sum == S) {
res++;
}
sum = 0;
return;
}
isCheck[current] = true;
dfs(current+1);
isCheck[current] = false;
dfs(current+1);
}
}
๐ค ๋์ ์๊ฐ
๋ถ๋ถ์งํฉ์ ํฉ์ผ๋ก ํ์ด์ฃผ์๋ค.
๊ฒฐ๊ตญ ํฉ์ด S์ธ ๊ฒ์ ๊ตฌํ๋ ๊ฒ์ด๊ธฐ ๋๋ฌธ์ ๊ฐ๊ฐ์ ์์๋ฅผ ๋ค ๋์์ฃผ๋ฉด์ ๋ํด์ ํฉ์ด S๊ฐ ๋๋ฉด ์นด์ดํ
์ ํด์ฃผ๊ณ ๋ฆฌํดํด์ค๋ค.