Here is a technique to calculate nCr using DP.
From pascal's triangular relation, we get,
nCr =( n-1)C(r) + (n-1)C(r-1)
The basic idea lies behind DP-
nCn = 1
nC1 = n
nC0 = 1
and
nCr = n-1Cr + n-1Cr-1
So the code forms like following-
From pascal's triangular relation, we get,
nCr =( n-1)C(r) + (n-1)C(r-1)
The basic idea lies behind DP-
nCn = 1
nC1 = n
nC0 = 1
and
nCr = n-1Cr + n-1Cr-1
So the code forms like following-
#define i64 unsigned long long
i64 dp[66][33];
i64 nCr(int n, int r)
{
if(n==r) return dp[n][r] = 1;
if(r==0) return dp[n][r] = 1;
if(r==1) return dp[n][r] = (i64)n;
if(dp[n][r]) return dp[n][r];
return dp[n][r] = nCr(n-1,r) + nCr(n-1,r-1);
}
No comments:
Post a Comment