for k inrange(1, k + 1): for i inrange(m): for j inrange(n): # 水平方向切 for i2 inrange(i + 1, m): if apples[i][j] > apples[i2][j]: dp[k][i][j] = (dp[k][i][j] + dp[k - 1][i2][j]) % mod # 垂直方向切 for j2 inrange(j + 1, n): if apples[i][j] > apples[i][j2]: dp[k][i][j] = (dp[k][i][j] + dp[k - 1][i][j2]) % mod return dp[k][0][0]
funcways(pizza []string, k int)int { m := len(pizza) n := len(pizza[0]) mod := 1_000_000_007 apples := make([][]int, m + 1) for i := range apples { apples[i] = make([]int, n + 1) } dp := make([][][]int, k + 1) for i := range dp { dp[i] = make([][]int, m + 1) for j := range dp[i] { dp[i][j] = make([]int, n + 1) } }
// 预处理 for i := m - 1; i >= 0; i-- { for j := n - 1; j >= 0; j-- { apples[i][j] = apples[i + 1][j] + apples[i][j + 1] - apples[i+1][j + 1] if pizza[i][j] == 'A' { apples[i][j] += 1 } if apples[i][j] > 0 { dp[1][i][j] = 1 } } }
for ki := 2; ki <= k; ki++ { for i := 0; i < m; i++ { for j := 0; j < n; j++ { // 水平方向切 for i2 := i + 1; i2 < m; i2++ { if apples[i][j] > apples[i2][j] { dp[ki][i][j] = (dp[ki][i][j] + dp[ki - 1][i2][j]) % mod } } // 垂直方向切 for j2 := j + 1; j2 < n; j2++ { if apples[i][j] > apples[i][j2] { dp[ki][i][j] = (dp[ki][i][j] + dp[ki - 1][i][j2]) % mod } } } } } return dp[k][0][0] }
intways(char ** pizza, int pizzaSize, int k){ int m = pizzaSize, n = strlen(pizza[0]), mod = 1e9 + 7; int apples[m + 1][n + 1]; int dp[k + 1][m + 1][n + 1]; memset(apples, 0, sizeof(apples)); memset(dp, 0, sizeof(dp));
// 预处理 for (int i = m - 1; i >= 0; i--) { for (int j = n - 1; j >= 0; j--) { apples[i][j] = apples[i][j + 1] + apples[i + 1][j] - apples[i + 1][j + 1] + (pizza[i][j] == 'A'); dp[1][i][j] = (apples[i][j] > 0) ? 1 : 0; } }
for (int ki = 2; ki <= k; ki++) { for (int i = 0; i < m; i++) { for (int j = 0; j < n; j++) { dp[ki][i][j] = 0; // 水平方向切 for (int i2 = i + 1; i2 < m; i2++) { if (apples[i][j] > apples[i2][j]) { dp[ki][i][j] = (dp[ki][i][j] + dp[ki - 1][i2][j]) % mod; } } // 垂直方向切 for (int j2 = j + 1; j2 < n; j2++) { if (apples[i][j] > apples[i][j2]) { dp[ki][i][j] = (dp[ki][i][j] + dp[ki - 1][i][j2]) % mod; } } } } } return dp[k][0][0]; }
复杂度分析
时间复杂度:O(kmn(n + m)),其中 n 和 m 是矩形的行数和列数,k 是披萨的切割数量。