Post

[BaekJoon] #11050 - 이항 계수 1 [Java][C++]

[BaekJoon] #11050 - 이항 계수 1 [Java][C++]

문제 링크


1. 아이디어

자연수 $N$과 정수 $K$가 주어졌을 때 이항 계수를 구하는 문제로 파스칼의 항등식을 활용한 재귀로 해결할 수 있다.

파스칼의 삼각형을 통해 알 수 있는 파스칼의 항등식은 아래와 같다.


\[\binom{n}{r} = \binom{n - 1}{r} + \binom{n - 1}{r - 1}\]


종료 조건은 아래와 같이 설정하면 된다.


\[\binom{n}{0} = \binom{n}{n} = 1 \qquad\text{and}\qquad \binom{n}{1} = n\]



2. 복잡도

접근시간공간
풀이$O(2^N)$$O(N)$

($N$ = 입력값 n)


3. 코드

풀이 [Java][C++]

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
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(comb(n, k));
    }

    static int comb(int n, int r) {
        if (r == 0 || n == r) return 1;
        if (r == 1) return n;
        return comb(n - 1, r) + comb(n - 1, r - 1);
    }
}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
#include <bits/stdc++.h>
using namespace std;

int comb(int n, int r) {
    if (r == 0 || n == r) return 1;
    if (r == 1) return n;
    return comb(n - 1, r) + comb(n - 1, r - 1);
}

int main() {
    ios::sync_with_stdio(0);
    cin.tie(0);

    int n, k;
    cin >> n >> k;
    cout << comb(n, k);
}

This post is licensed under CC BY 4.0 by the author.