본문 바로가기

프로그래머스/lv0

구슬을 나누는 경우의 수

/* 구슬을 나누는 경우의 수
 * 구슬은 모두 다르게 생겼습니다.
 * 갖고 있는 구슬의 개수 balls와 나누어 줄 구슬 개수 share이 매개변수로 주어질 때,
 * balls개의 구슬 중 share개의 구슬을 고르는 가능한 모든 경우의 수를 return
 *
 * balls    share   result
 * 3        2       3       서로 다른 구슬 3개 중 2개를 고르는 경우의 수는 3입니다.
 * 5        3       10      서로 다른 구슬 5개 중 3개를 고르는 경우의 수는 10입니다.
 *
 * 서로 다른 n개 중 m개를 뽑는 경우의 수 공식은 다음과 같습니다.
 * n! / (n-m)! * m!
 */

 

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
import java.math.BigInteger;
public class Programmer_0_75 {
    static int a1 = 30static int b1 = 1
    static int a2 = 5static int b2 = 3
    public BigInteger getFac(int n){
        BigInteger rst = BigInteger.ONE;
        for(int i = 1; i <= n; i++){
            rst = rst.multiply(BigInteger.valueOf(i));
        }
        return rst;
    }
    public int solution(int balls, int share) {
        int answer = 0;
        
        // if(balls != share) answer = getFac(balls).divide((getFac(balls - share).multiply(getFac(share)))).intValue();
        // else    answer = 1;
 
        // /* 다른사람 풀이
        share = Math.min(balls - share, share); //두개 중 작은 값 반환
        System.out.println("share = " + share);
        if(share == 0)  return 1;
        long result = solution(balls - 1 , share - 1);
        result *= balls;
        result /= balls;
        //  */
 
        return answer;
    }
    
    public static void main(String args[]){
        Programmer_0_75 t = new Programmer_0_75();
 
        System.out.println("---------------------------------------");
        System.out.println("result = " + t.solution(a1,b1));
        System.out.println("---------------------------------------");
        // System.out.println("result2 = " + t.solution(a2,b2));
        // System.out.println("---------------------------------------");
    }
}
cs

'프로그래머스 > lv0' 카테고리의 다른 글

진료순서 정하기  (0) 2022.12.02
모스부호 (1)  (2) 2022.12.02
2차원으로 만들기  (0) 2022.12.02
공 던지기  (0) 2022.12.02
배열 회전시키기  (0) 2022.12.02