A useful application of Pascal’s triangle is the calculation of combinations. The formula to find nCr is n! / r! * (n – r)! which is also the formula for a cell of Pascal’s triangle.
Input: n = 5, r = 3 Output: 10 Explanation: n! / r! * (n - r)! = 5! / 3! * (2!) = 120 / 12 = 10 Input: n = 7, r = 2 Output: 21 Explanation: n! / r! * (n - r)! = 7! / 5! * (2!) = 42 / 2 = 21
Approach: The idea is to store the Pascal’s triangle in a matrix then the value of nCr will be the value of the cell at nth row and rth column.
To create the pascal triangle use this two formula:
- nC0 = 1, number of ways to select 0 elements from a set of n elements is 0
- nCr = n-1Cr-1 + n-1Cr, number of ways to select r elements from a set of n elements is summation of ways to select r-1 elements from n-1 elements and ways to select r elements from n-1 elements.
The idea is to use the values of subproblems to calculate the answers for larger values. For example, to calculate nCr, use the values of n-1Cr-1 and n-1Cr. So DP can be used to preprocess all the values in the range.
- Create a matrix of size 1000 * 1000, assign the value of base cases, i.e. run a loop from 0 to 1000 and assign matrix[i] = 1, nC0 = 1
- Run a nested loop from i = 1 to 1000 (outer loop) and the inner loop runs from j = 1 to i + 1.
- For every element (i, j) assign the value of matrix[i][j] = matrix[i-1][j-1] + matrix[i-1][j], using the formula nCr = n-1Cr-1 + n-1Cr
- After filling the matrix return the value of nCr as matrix[n][r]
- Time Complexity: O(1).
The value of all pairs are precomputed so the time to answer the query is O(1), though some time is taken for precomputation but theoretically the precomputation takes constant time.
- Space Complexity: O(1).
Constant space is required.
Attention reader! Don’t stop learning now. Get hold of all the important DSA concepts with the DSA Self Paced Course at a student-friendly price and become industry ready. Get hold of all the important mathematical concepts for competitive programming with the Essential Maths for CP Course at a student-friendly price.