프로그래머스 입문 구슬을 나누는 경우의 수 [JAVA] - 23년 3월 4일

Denia·2023년 3월 4일
0

코딩테스트 준비

목록 보기
166/201

조합을 재귀로 풀기 - 복습


class Solution {

    private int answer, balls, share;

    public int solution(int balls, int share) {
        answer = 0;
        this.balls = balls;
        this.share = share;

        for (int i = 0; i < balls; i++) {
            combination(i, 1);
        }

        return answer;
    }

    private void combination(int curIdx, int curCount) {
        if (curCount == share) {
            answer++;
            return;
        }

        for (int i = curIdx + 1; i < balls; i++) {
            combination(i, curCount + 1);
        }
    }
}

공식으로 풀기

그냥 공식대로 풀려고 하니까
오버플로우 + 부동소수점 때문에 값이 자꾸 틀리게 나왔다.

조금 다른 방식으로 접근을 해야 풀 수 있을 것 같다

BigInt를 써도 풀이가 되지만 미리 미리 나누기 및 곱하기를 해줘야 할 것 같다.

class Solution {

    public long solution(int balls, int share) {
        long answer = 0;

        answer = factorial(balls) / (factorial(balls - share)) * factorial(share);

        return answer;
    }

    private long factorial(int n) {
        if (n == 0) {
            return 1;
        } else {
            return n * factorial(n - 1);
        }
    }
}
profile
HW -> FW -> Web

0개의 댓글