조합의 경우수

Changwook Yang·2023년 1월 15일

알고리즘 연습

목록 보기
9/41

조합의 경우수(메모이제이션)

nCr = n-1Cr-1 + n-1Cr 을 통하여 조합의 수를 구하라

import java.util.Scanner;

public class Main {

    static int n, r;
    static int[][] arr;

    public static void main(String[] args) {
        Scanner scanner = new Scanner(System.in);
        n = scanner.nextInt();
        r = scanner.nextInt();

        arr = new int[n + 1][r + 1];

        arr[1][1] = 1;

        int combination = combination(n, r);
        System.out.println(combination);

    }

    private static int combination(int current, int r) {
        if (current == r || r == 0) return 1;

        if (arr[current][r] > 0) {
            return arr[current][r];
        } else {
            int value = combination(current - 1, r - 1) + combination(current - 1, r);
            arr[current][r] = value;
            return value;
        }
    }


}
profile
멋있는 백엔드 개발자 / 꾸준히 의미있게!

0개의 댓글