使用递归计算 nCr 值的程序
给定两个数字N和r ,使用递归找到N C r的值
例子:
Input: N = 5, r = 2
Output: 10
Explanation: The value of 5C2 is 10
Input: N = 3, r = 1
Output: 3
方法:这个想法只是基于以下公式。
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)
所以,
NCr = NCr-1 * (N-r+1) / r
下面是上述方法的实现:
C++
// C++ code to implement above approach
#include
using namespace std;
// Function to calculate the value of nCr
// using recursion
int nCr(int N, int r)
{
int res = 0;
if (r == 0) {
return 1;
}
else {
res = nCr(N, r - 1)
* (N - r + 1) / r;
}
return res;
}
// Driver code
int main()
{
int N = 5, r = 3;
cout << nCr(N, r);
return 0;
}
Java
// Java code for the above approach
import java.io.*;
class GFG {
// Function to calculate the value of nCr
// using recursion
static int nCr(int N, int r)
{
int res = 0;
if (r == 0) {
return 1;
}
else {
res = nCr(N, r - 1) * (N - r + 1) / r;
}
return res;
}
public static void main(String[] args)
{
int N = 5, r = 3;
System.out.println(nCr(N, r));
}
}
// This code is contributed by Potta Lokesh
Python3
# Python code to implement above approach
# Function to calculate the value Of nCr
# using recursion
def nCr(N, r):
res = 0
if(r == 0):
return 1
else:
res = nCr(N, r-1)
* (N-r + 1) / r
return res
# Driver code
if __name__ == "__main__":
N = 5
r = 3
print(int(nCr(N, r)))
C#
using System;
public class GFG{
// Function to calculate the value of nCr
// using recursion
static int nCr(int N, int r)
{
int res = 0;
if (r == 0) {
return 1;
}
else {
res = nCr(N, r - 1)
* (N - r + 1) / r;
}
return res;
}
// Driver code
static public void Main (){
int N = 5, r = 3;
Console.WriteLine(nCr(N, r));
}
}
// This code is contributed by hrithikgarg03188.
Javascript
输出
10
时间复杂度:O(N!)
辅助空间:O(1)