To get the "number of divisions" counter, you can use Dynamic Programming , which follows the recursive formula:
D(0,0,j) = 1 D(x,0,j) = 0 x > 0 D(x,i,j) = 0 x < 0 or j<0 D(x,i,j) = D(xj,i-1,j) + D(x,i,j-1)
The answer denoted by D(n,k,m) is the number of such divisions.
Difficulty O(n*k*m)
Java Code:
public static int numDivisions(int n, int m, int k) { int[][][] D = new int[n+1][k+1][m]; for (int j = 0; j < m; j++) { for (int x = 0; x <= n; x++) { D[x][0][j] = 0; } D[0][0][j] = 1; } for (int i = 1; i <= k; i++) { for (int x = 0; x <= n; x++) { for (int j = 0; j < m; j++) { D[x][i][j] = 0; if (j > 0) D[x][i][j] += D[x][i][j-1]; if (xj-1 >=0) D[x][i][j] += D[xj-1][i-1][j]; } } } return D[n][k][m-1]; }
As a side note, this seems like a stars and bars problem, but the order doesn't matter here, and besides that, you have the top one related to the number of βstarsβ in the cell.
source share