[프로그래머스/C++]Lv.0 - 구슬을 나누는 경우의 수

YH J·2023년 4월 19일
0

프로그래머스

목록 보기
54/168

문제 링크

https://school.programmers.co.kr/learn/courses/30/lessons/120840

내 풀이


공식은 Hint에 나와있으니 이대로 하면 되는데 값이 너무 커져서 int형으로 하면 오버플로우가 나므로 double형을 사용하였다.

내 코드

#include <string>
#include <vector>

using namespace std;

int solution(int balls, int share) {
    int answer = 1;
    double a = 1;
    
    if(balls == share)
        return 1;
    
    for(int i = 1; i <= share; i++)
    {
        a /= (double)i;
        a *= (double)(balls-i+1);
    }
    
    return (int)a;
}

다른 사람의 풀이

#include <string>
#include <vector>

using namespace std;

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

int solution(int balls, int share) {
    int answer = 0;
    answer = combi(balls, share);
    return answer;
}

다른 사람의 풀이 해석

https://ansohxxn.github.io/algorithm/combination/
조합(Combination) 구현하는 방법이다. 재귀함수를 사용한다.

profile
게임 개발자 지망생

0개의 댓글