λ°μν
μ½λ
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.StringTokenizer;
public class Solution {
/*
* N: μμ°μ κ°―μ
* K: μμ°μλ₯Ό μ νν΄μ ν©μ΄ Kκ° λλ κ²½μ°
* arr[]: Nκ°μ μμ°μλ₯Ό λ΄μ λ°°μ΄
* ans: κ²½μ°μ μ
*/
private static int N;
private static int K;
private static int arr[];
private static int ans;
private static void dfs(int count, int sum) {
/* κΈ°μ μ¬λ‘: μμ°μ xκ° μ νν΄μ ν©μ΄ Kκ° λλ κ²½μ° */
if(sum == K) {
ans ++;
return;
}
/* κΈ°μ μ¬λ‘: μμ°μ xκ°μ ν©μ΄ Kλ³΄λ€ ν°κ²½μ° || μ νν μμ°μμ κ°―μκ° Nκ°μ λμΌν κ²½μ°*/
if(sum > K || count == N) {
return;
}
// μκΈ° μμ ν¬ν¨
dfs(count+1, sum+arr[count]);
// μκΈ° μμ λ―Έν¬ν¨
dfs(count+1, sum);
}
public static void main(String[] args) throws NumberFormatException, IOException {
BufferedReader bf = new BufferedReader(new InputStreamReader(System.in));
StringTokenizer st;
StringBuilder sb = new StringBuilder();
int t = Integer.parseInt(bf.readLine());
for(int tc=1; tc<=t; tc++) {
st = new StringTokenizer(bf.readLine());
N = Integer.parseInt(st.nextToken());
K = Integer.parseInt(st.nextToken());
arr = new int[N];
ans = 0;
st = new StringTokenizer(bf.readLine());
for(int i=0; i<N; i++) {
arr[i] = Integer.parseInt(st.nextToken());
}
dfs(0, 0);
System.out.println("#" + tc + " " + ans);
}
bf.close();
}
}
νμ΄
nCr μ‘°ν© λ¬Έμ .
μ¬κ·ν¨μλ₯Ό ν΅ν΄ ν΄κ²°νκ³ , μ¬κ·ν¨μμ μ’ λ£ μ‘°κ±΄μ λ€μκ³Ό κ°λ€.
- κ³ λ₯Έ μμ°μμ ν©μ΄ Kμ λμΌν κ²½μ°
- κ³ λ₯Έ μμ°μμ ν©μ΄ Kλ³΄λ€ ν¬κ±°λ, κ³ λ₯Έ μμ°μμ κ°―μκ° Nκ°μΌ κ²½μ°
dfs μ¬κ· νΈμΆμ ν΅ν΄ νμ¬ μ νλ μ«μλ₯Ό ν¬ν¨νλ κ²½μ°
- dfs(count+1, sum+arr[count])
νμ¬ μ νλ μ«μλ₯Ό ν¬ν¨νμ§ μκ³ λ€μμΌλ‘ κ°λ κ²½μ°
- dfs(count+1, sum)
λ‘ λλμ΄ νμμ μ§νν¨.
λ°μν
'Algorithm' μΉ΄ν κ³ λ¦¬μ λ€λ₯Έ κΈ
[SW Expert Academy] - (D1)2072. νμλ§ λνκΈ°(Stream) (4) | 2020.08.05 |
---|---|
[λ°±μ€] 2562λ²: μ΅λκ°(Stream) (0) | 2020.08.04 |
[SW Expert Academy] - (D3)4299. ννμ΄μ μ¬λμ νμ΄λ° (0) | 2020.07.17 |
[SW Expert Academy] - (D3)8931. μ λ‘(Stack) (0) | 2020.07.12 |
[SW Expert Academy] - (D3)9997. λ―Έλλ©λ¦¬μ¦ μκ³ (0) | 2020.07.10 |
λκΈ