[BaekJoon] 11050번 - 이항 계수 1 [Java]
[BaekJoon] 11050번 - 이항 계수 1 [Java]
문제 풀이
자연수 $N$ 과 정수 $K$ 가 주어졌을 때 이항 계수를 구하는 문제로 파스칼의 항등식을 활용한 재귀로 해결할 수 있다.
파스칼의 삼각형을 통해 알 수 있는 파스칼의 항등식은 아래와 같다.
종료 조건은 아래와 같이 설정해주면 된다.
코드
1. 풀이 [Java]
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
import java.io.*;
import java.util.*;
public class Main {
public static void main(String[] args) throws IOException {
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
StringTokenizer st = new StringTokenizer(br.readLine());
int N = Integer.parseInt(st.nextToken());
int K = Integer.parseInt(st.nextToken());
System.out.println(nCr(N, K));
}
static int nCr(int n, int r) {
if (r == 0 || n == r) return 1;
if (r == 1) return n;
return nCr(n - 1, r) + nCr(n - 1, r - 1);
}
}
2. 풀이 [C++]
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
#include <bits/stdc++.h>
using namespace std;
int nCr(int n, int r) {
if (r == 0 || n == r) return 1;
if (r == 1) return n;
return nCr(n - 1, r) + nCr(n - 1, r - 1);
}
int main() {
ios::sync_with_stdio(false);
cin.tie(nullptr);
int n, k;
cin >> n >> k;
cout << nCr(n, k);
}
This post is licensed under CC BY 4.0 by the author.