top of page
Caută
  • Poza scriitoruluioanaunciuleanu

Binomial Coefficient in JAVA

Write a function that accepts two parameters n and k, and returns the value of the Binomial Coefficient C(n, k).

Input: n = 4, k = 2 Output: 6 Explanation: There are 6 ways to choose 2 elements from {1, 2, 3, 4}: {1, 2}, {1, 3}, {1, 4}, {2, 3}, {2, 4} and {3, 4}. Input: n = 5, k = 2 Output: 10



Solution:


1. static int binomialCoefficient(int n, int k) { 2. int[] coefficients = new int[k + 1]; 3. coefficients[0] = 1; 4. 5. for (int i = 1; i <= n; i++) { 6. for (int j = Math.min(i, k); j > 0; j--) 7. coefficients[j] = coefficients[j] + coefficients[j - 1]; 8. } 9. return coefficients[k]; 10. }




5 afișări0 comentarii

Postări recente

Afișează-le pe toate

Weighted Job Scheduling in JAVA

You receive a list of jobs that have three elements: start time, finish time and profit. You have to schedule the jobs with no overlapping, in order to obtain the maximum profit. Solution: 1. static

Tiling Problem in JAVA

You can use a board that is 2 x n size. The tiles are of size 2 x 1. Count the number of ways to tile the board. Tiles can be placed vertically 2 x 1 or horizontally as 1 x 2. Solution: 1. static

bottom of page