1. 不浪費原料的漢堡製作方案(數學題)
難度:中等
聖誕活動預熱開始啦,漢堡店推出了全新的漢堡套餐。爲了避免浪費原料,請你幫他們制定合適的製作計劃。
給你兩個整數 tomatoSlices 和 cheeseSlices,分別表示番茄片和奶酪片的數目。不同漢堡的原料搭配如下:
- 巨無霸漢堡:4 片番茄和 1 片奶酪
- 小皇堡:2 片番茄和 1 片奶酪
請你以 [total_jumbo, total_small]([巨無霸漢堡總數,小皇堡總數])的格式返回恰當的製作方案,使得剩下的番茄片 tomatoSlices 和奶酪片 cheeseSlices 的數量都是 0。
如果無法使剩下的番茄片 tomatoSlices 和奶酪片 cheeseSlices 的數量爲 0,就請返回 []。
示例 1:
輸入:tomatoSlices = 16, cheeseSlices = 7
輸出:[1,6]
解釋:製作 1 個巨無霸漢堡和 6 個小皇堡需要 41 + 26 = 16 片番茄和 1 + 6 = 7 片奶酪。不會剩下原料。
示例 2:
輸入:tomatoSlices = 17, cheeseSlices = 4
輸出:[]
解釋:只製作小皇堡和巨無霸漢堡無法用光全部原料。
示例 3:
輸入:tomatoSlices = 4, cheeseSlices = 17
輸出:[]
解釋:製作 1 個巨無霸漢堡會剩下 16 片奶酪,製作 2 個小皇堡會剩下 15 片奶酪。
示例 4:
輸入:tomatoSlices = 0, cheeseSlices = 0
輸出:[0,0]
示例 5:
輸入:tomatoSlices = 2, cheeseSlices = 1
輸出:[0,1]
提示:
- 0 <= tomatoSlices <= 10^7
- 0 <= cheeseSlices <= 10^7
解決方案:
class Solution:
def numOfBurgers(self, tomatoSlices: int, cheeseSlices: int) -> List[int]:
res = []
if tomatoSlices%2 != 0:
return res
x = tomatoSlices//2 - cheeseSlices
y = 2 * cheeseSlices - tomatoSlices//2
if x < 0 or y < 0:
return res
res.append(x)
res.append(y)
return res
執行用時 | 內存消耗 | 語言 |
---|---|---|
64 ms | 13.7 MB | Python3 |
2. 統計全爲 1 的正方形子矩陣(動態規劃)
難度:中等
給你一個 m * n 的矩陣,矩陣中的元素不是 0 就是 1,請你統計並返回其中完全由 1 組成的 正方形 子矩陣的個數。
示例 1:
輸入:matrix =
[
[0,1,1,1],
[1,1,1,1],
[0,1,1,1]
]
輸出:15
解釋:
邊長爲 1 的正方形有 10 個。
邊長爲 2 的正方形有 4 個。
邊長爲 3 的正方形有 1 個。
正方形的總數 = 10 + 4 + 1 = 15.
示例 2:
輸入:matrix =
[
[1,0,1],
[1,1,0],
[1,1,0]
]
輸出:7
解釋:
邊長爲 1 的正方形有 6 個。
邊長爲 2 的正方形有 1 個。
正方形的總數 = 6 + 1 = 7.
提示:
- 1 <= arr.length <= 300
- 1 <= arr[0].length <= 300
- 0 <= arr[i][j] <= 1
解決方案:
class Solution:
def countSquares(self, matrix: List[List[int]]) -> int:
n=len(matrix)
m=len(matrix[0])
ans=0
for i in range(0,m):
ans+=matrix[0][i]
for i in range(1,n):
ans+=matrix[i][0]
for i in range(1,n):
for j in range(1,m):
if matrix[i][j]:
matrix[i][j]=min(matrix[i-1][j-1],matrix[i][j-1],matrix[i-1][j])+1
ans+=matrix[i][j]
return ans
執行用時 | 內存消耗 | 語言 |
---|---|---|
864 ms | 16 MB | Python3 |
3. 分割回文串 III(動態規劃)
難度:困難
給你一個由小寫字母組成的字符串 s,和一個整數 k。
請你按下面的要求分割字符串:
- 首先,你可以將 s 中的部分字符修改爲其他的小寫英文字母。
- 接着,你需要把 s 分割成 k 個非空且不相交的子串,並且每個子串都是迴文串。
請返回以這種方式分割字符串所需修改的最少字符數。
示例 1:
輸入:s = “abc”, k = 2
輸出:1
解釋:你可以把字符串分割成 “ab” 和 “c”,並修改 “ab” 中的 1 個字符,將它變成迴文串。
示例 2:
輸入:s = “aabbc”, k = 3
輸出:0
解釋:你可以把字符串分割成 “aa”、“bb” 和 “c”,它們都是迴文串。
示例 3:
輸入:s = “leetcode”, k = 8
輸出:0
提示:
- 1 <= k <= s.length <= 100
- s 中只含有小寫英文字母。
解決方案(來自網友):
class Solution:
def palindromePartition(self, s: str, k: int) -> int:
n=len(s)
cost=[[0]*n for _ in range(n)]
t=0
for t in range(1,n):
for i in range(0,n-t):
j=i+t
cost[i][j]=cost[i+1][j-1]+(s[i]!=s[j])
dp=[[0]*k for _ in range(n)]
for i in range(n):
dp[i][0]=cost[0][i]
for i in range(0,n):
for j in range(1,k):
m=float("inf")
for l in range(j-2,i):
m=min(m,cost[l+1][i]+dp[l][j-1])
dp[i][j]=m
return dp[-1][-1]