以迭代形式查找二项式系数的代码

时间:2017-08-30 17:55:22

标签: java recursion iteration binomial-coefficients

我编写了以递归形式查找二项式系数的代码:

public int binom(int n, int k)
{
    if (k==n || k==0)
        return 1;
    else return binom(n-1,k-1) + binom(n-1, k);
}

如何以迭代形式而不是递归形式重写此代码?

2 个答案:

答案 0 :(得分:2)

public int binom(int n, int k)
    {
        int C[][] = new int[n+1][k+1];
        int i, j;
        int min;

        // Caculate value of Binomial Coefficient in bottom up manner
        for (i = 0; i <= n; i++)
        {
            min = (i<k)? i: k;

            for (j = 0; j <= min; j++)
            {
                // Base Cases
                if (j == 0 || j == i)
                    C[i][j] = 1;

                    // Calculate value using previosly stored values
                else
                    C[i][j] = C[i-1][j-1] + C[i-1][j];
            }
        }

        return C[n][k];
    }

答案 1 :(得分:1)

Instead of building the entire Pascal triangle up to the n-th row (memory usage grows quadratically with n), we can simply focus on the row itself, and use constant memory.

Let's find a relationship between consecutive terms on the same row on Pascal's triangle:

enter image description here

Thus we can iteratively generate the terms from nC0 = 1:

const user = await User.findById(someId).exec()
const answer = await Answer.findById(someAnswerId).exec()
const question = await Question.findBYId(someQuestionId).exec()

user.favoriteAnswers.addToSet(answer._id)
user.favoriteQuestions.addToSet(question._id)
await user.save()