[JAVA 문제 풀이] 27. 구슬을 나누는 경우의 수(120840)

Stupefyee's avatar
Nov 21, 2024
[JAVA 문제 풀이] 27. 구슬을 나누는 경우의 수(120840)
notion image
notion image

내가 작성한 코드

💡
class Solution { public int solution(int balls, int share) { long answer = 1; int shareIndex = 1; for(int i = share+1; i <= balls; i++){ answer *= i; answer /= shareIndex; shareIndex++; } return (int)answer; } }
풀이 과정
분자의 경우 : n * n-1 * n-2 * n-3 ······ 3 * 2 * 1
분모의 경우 : (n-m* n-m-1 ······ 2 * 1) * (m* m-1 * m-2 * ······ * 2 * 1)
⇒ 분모는 m! 분자는 n!을 하되 m만큼만 하기
예시) n = 5, m = 2 ⇒ m = 2 * 1, n = 5 * 4(m이 2니까 5랑 4만 곱함)

다른 사람의 코드

💡
class Solution { public long solution(int balls, int share) { long answer = 0; int d = (balls - share) > share ? share : balls - share; if (d == 0) return 1; return solution(balls - 1, d - 1) * balls / d; } }
 
Share article

stupefyee