![]() |
VOOZH | about |
Given two integers n and r, the task is to compute the value of nCr (i.e., the number of ways to choose r elements from a set of n elements) using Recursion.
Examples:
Input: n = 5, r = 2
Output: 10
Explanation: There are 10 ways to choose 2 elements from 5. Using recursion: 5C2 = 4C1 + 4C2 = 4 + 6 = 10.Input: n = 3, r = 1
Output: 3
Explanation: Choosing 1 element from 3 can be done in 3 ways. Base case applies directly.Input: n = 6, r = 3
Output: 20
Table of Content
The idea is to use recursion to break down the original combination problem into smaller subproblems by repeatedly reducing either n or r, and summing up their results until the base cases are met.
Recursive Relation:
The recursive relation lies in this line: return nCr(n - 1, r - 1) + nCr(n - 1, r);
This is based on Pascal’s Rule: nCr = (n-1)C(r-1) + (n-1)Cr
Here:
- (n - 1, r - 1) considers choosing the current element.
- (n - 1, r) considers skipping the current element.
- The sum of both gives total ways to choose r elements from n.
At every recursive step, the function branches into two subproblems, reducing the problem size until it reaches a known base value.
Base Cases:
The base cases are:
- if (r == 0 || r == n) return 1;
- if (r == 1) return n;
These serve as the termination conditions:
- r == 0 or r == n: Only one way to choose none or all elements.
- r == 1: Exactly n ways to choose one element from n.
10
Time Complexity: O(2^n), Every call branches into two, creating a binary recursion tree.
Space Complexity: O(n), Maximum depth of recursive calls is n.
The idea is to compute nCr recursively using a mathematical transformation rather than expanding full factorials. The thought process is to simplify the standard formula for nCr using a relation with its previous value, which avoids redundant computation. The observation here is that each nCr can be derived from nCr-1 by multiplying with (n - r + 1) and dividing by r, leading to an efficient recursion. This reduces the recursive tree depth compared to the previous approach.
Derivation:
nCr = n! / (r! * (n-r)!)
Also, nCr-1 = n! / ((r-1)! * (n - (r-1))!)Hence,
- nCr * r! * (n - r)! = nCr-1 * (r-1)! * (n - (r-1))!
- nCr * r * (n-r)! = nCr-1 * (n-r+1)! [eliminating (r - 1)! from both side]
- nCr * r = nCr-1 * (n-r+1)
Therefore,
nCr = nCr-1 * (n-r+1) / r
10
Time Complexity: O(r), Each call reduces r by 1 until it hits 0 or 1.
Space Complexity: O(r), Due to recursive stack space proportional to r.