조합(Combination)

- 서로 다른 n개 중에서 r개를 선택하는 경우의 수(순서 X, 중복 X)

ex) 서로 다른 4명 중 주번 2명 뽑는 방법


중복 조합

- 서로 다른 n개 중에서 r개를 선택하는 경우의 수(순서 X, 중복 O)

ex) 후보 2명, 유권자 3명일 때 무기명 투표 방법


실습 코드

// 기초 수학 - 조합

public class Main {

    static int getCombination(int n, int r) {
        int pResult = 1; // 결과를 저장할 변수
        for (int i = n; i >= n - r + 1; i--) {
            pResult *= i;
        }
        int rResult = 1;
        for (int i = 1; i <= r ; i++) {
            rResult *= i;
        }
        return pResult / rResult;
    }
    public static void main(String[] args) {
//      1. 조합
        System.out.println("== 조합 ==");

        int n = 4;
        int r = 2;
// nPr을 먼저(분자) nPr = n! / (n-r)!
        int pResult = 1; // 결과를 저장할 변수
        for (int i = n; i >= n - r + 1; i--) {
            pResult *= i;
        }
        int rResult = 1;
        for (int i = 1; i <= r ; i++) {
            rResult *= i;
        }
        System.out.println("결과 : " + pResult / rResult);

//      2. 중복 조합
        // nHr = n+r-1Cr
        System.out.println("== 중복 조합 ==");
        n = 2;
        r = 3;

        System.out.println("결과 : " + getCombination(n + r - 1, r));
    }
}

조합 연습 코드

// Practice
// 1, 2, 3, 4 를 이용하여 세자리 자연수를 만드는 방법 (순서 X, 중복 x)의 각 결과를 출력하시오

public class Practice {
    void combination(int[] arr, boolean[] visited, int depth, int n, int r) {

        if (r == 0) {
            for (int i = 0; i < n; i++) {
                if (visited[i]) {
                    System.out.print(arr[i] + " ");
                }
            }
            System.out.println();
            return;
        }
        if (depth == n) {
            return;
        }
        visited[depth] = true;
        combination(arr, visited, depth + 1, n, r - 1);

        visited[depth] = false;
        combination(arr, visited, depth + 1, n, r);
    }
    public static void main(String[] args) {
//      Test code
        int[] arr = {1, 2, 3, 4};
        boolean[] visited = {false, false, false, false};

        Practice p = new Practice();
        p.combination(arr, visited, 0, 4, 3);
    }
}

 

이해하기 위한 발악... 대충 이해는 했는데 나중에 까먹지 않기 위해 우선 같이 올려둠

'자료구조 l 알고리즘 > Ch. 01. 기초 수학' 카테고리의 다른 글

지수와 로그  (0) 2023.03.16
점화식과 재귀함수  (0) 2023.03.16
순열  (0) 2023.03.14
경우의 수  (0) 2023.03.14
집합  (0) 2023.03.13