0

I have the following method that needs to be implemented iteratively:

public int binom(int n, int k) {
        if (k < 0 || k > n) {
            return 0;
        }

        if (k == 0 || k == n) {
            return 1;
        }

        return binom(n - 1, k - 1) + binom(n - 1, k);
    }

The only condition is that I have to use the identity:

binom(n, k) = binom(n - 1, k - 1) + binom(n - 1, k)

I ended up with the following:

public int binom(int n, int k) {

    if (k < 0 || k > n) {
        return 0;
    }

    if (k == 0 || k == n) {
        return 1;
    }

    int[] previousRow = {1, 1};

    for (int i = 2; i < n; i++) {
        int[] currentRow = new int[i+1];
        for (int j = 0; j <= i; j++) {
            if (j == 0 || j == i) {
                currentRow[j] = 1;
                continue;
            }

            currentRow[j] = previousRow[j-1] + previousRow[j];
        }
        previousRow = currentRow;
    }

    return previousRow[k - 1] + previousRow[k];
}

Is there a simpler/more obvious way to accomplish this that I'm missing?

Marcs
  • 3,768
  • 5
  • 33
  • 42
Detonator
  • 21
  • 4

0 Answers0