Which is better way to calculate nCr

前端 未结 5 662
情深已故
情深已故 2020-11-30 23:48

Approach 1:
C(n,r) = n!/(n-r)!r!

Approach 2:
In the book Combinatorial Algorithms by wilf, i have found this:
C(n,r) can be written as C(n-1,r) + C

5条回答
  •  臣服心动
    2020-12-01 00:13

    Your Recursive Approach is fine but using DP with your approach will reduce the overhead of solving subproblems again.Now since we already have two Conditions-

    nCr(n,r) = nCr(n-1,r-1) + nCr(n-1,r);
    
    nCr(n,0)=nCr(n,n)=1;
    

    Now we can easily build a DP solution by storing our subresults in a 2-D array-

    int dp[max][max];
    //Initialise array elements with zero
    int nCr(int n, int r)
    {
           if(n==r) return dp[n][r] = 1; //Base Case
           if(r==0) return dp[n][r] = 1; //Base Case
           if(r==1) return dp[n][r] = n;
           if(dp[n][r]) return dp[n][r]; // Using Subproblem Result
           return dp[n][r] = nCr(n-1,r) + nCr(n-1,r-1);
    }
    

    Now if you want to further otimise, Getting the prime factorization of the binomial coefficient is probably the most efficient way to calculate it, especially if multiplication is expensive.

    The fastest method I know is Vladimir's method. One avoids division all together by decomposing nCr into prime factors. As Vladimir says you can do this pretty efficiently using Eratosthenes sieve.Also,Use Fermat's little theorem to calculate nCr mod MOD(Where MOD is a prime number).

提交回复
热议问题