[Java 알고리즘 문제] (73) 구슬을 나누는 경우의 수

KangHo Lee's avatar
May 25, 2025
[Java 알고리즘 문제] (73) 구슬을 나누는 경우의 수

문제 설명

머쓱이는 구슬을 친구들에게 나누어주려고 합니다. 구슬은 모두 다르게 생겼습니다. 머쓱이가 갖고 있는 구슬의 개수 balls와 친구들에게 나누어 줄 구슬 개수 share이 매개변수로 주어질 때, balls개의 구슬 중 share개의 구슬을 고르는 가능한 모든 경우의 수를 return 하는 solution 함수를 완성해주세요.

제한사항

  • 1 ≤ balls ≤ 30
  • 1 ≤ share ≤ 30
  • 구슬을 고르는 순서는 고려하지 않습니다.
  • share ≤ balls

해답

import java.math.BigInteger; class Solution { public BigInteger solution(int balls, int share) { if (share == 0) return BigInteger.ONE; // 예외 방지 return factorial(balls) .divide(factorial(balls - share) .multiply(factorial(share))); } public static BigInteger factorial(int n) { BigInteger result = BigInteger.ONE; for (int i = 2; i <= n; i++) { result = result.multiply(BigInteger.valueOf(i)); } return result; } }
  • 팩토리얼 계산 중 int 범위를 초과하는 숫자 계산을 위해 BigInteger 사용
 
Share article

devleekangho