Skip to content

Commit 1e6f3ee

Browse files
solves Number of Ways of Cutting a Pizza (#1444) in python
1 parent 3b461dd commit 1e6f3ee

File tree

1 file changed

+24
-0
lines changed

1 file changed

+24
-0
lines changed
Lines changed: 24 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,24 @@
1+
# https://leetcode.com/problems/number-of-ways-of-cutting-a-pizza/
2+
# T: O(k*r*c*(m+n)) where k is the number of cuts, r and c are the number of rows and columns in the pizza, and m and n are the number of rows and columns in the preSum array.
3+
# S: O(k*r*c) where k is the number of cuts, and r and c are the number of rows and columns in the pizza.
4+
5+
class Solution:
6+
def ways(self, pizza: List[str], K: int) -> int:
7+
m, n, MOD = len(pizza), len(pizza[0]), 10 ** 9 + 7
8+
preSum = [[0] * (n + 1) for _ in range(m + 1)]
9+
for r in range(m - 1, -1, -1):
10+
for c in range(n - 1, -1, -1):
11+
preSum[r][c] = preSum[r][c + 1] + preSum[r + 1][c] - preSum[r + 1][c + 1] + (pizza[r][c] == 'A')
12+
@lru_cache(None)
13+
def dp(k, r, c):
14+
if preSum[r][c] == 0: return 0
15+
if k == 0: return 1
16+
ans = 0
17+
for nr in range(r + 1, m):
18+
if preSum[r][c] - preSum[nr][c] > 0:
19+
ans = (ans + dp(k - 1, nr, c)) % MOD
20+
for nc in range(c + 1, n):
21+
if preSum[r][c] - preSum[r][nc] > 0:
22+
ans = (ans + dp(k - 1, r, nc)) % MOD
23+
return ans
24+
return dp(K - 1, 0, 0)

0 commit comments

Comments
 (0)