Re: [閒聊] 每日LeetCode

作者: Rushia (みけねこ的鼻屎)   2023-09-24 16:55:16
https://leetcode.com/problems/champagne-tower/description
799. Champagne Tower
有一個香檳塔,第0層有一個杯子,第1層有兩個杯子(編號為0和1),以此類推,共有
100層杯子。
每個杯子可以裝1個單位的香檳,超出的部分會均勻的往下一層流,若我們往
香檳塔的頂部倒入poured單位的香檳,求出第query_row層的編號為query_glass的
杯子裡面有多少香檳。
https://s3-lc-upload.s3.amazonaws.com/uploads/2018/03/09/tower.png
Example:
Input: poured = 1, query_row = 1, query_glass = 1
Output: 0.00000
Explanation: We poured 1 cup of champange to the top glass of the tower
(which is indexed as (0, 0)). There will be no excess liquid so all the
glasses under the top glass will remain empty.
思路:
1.這個問題是一個遞迴問題,假如 f(i,j) 是第 i 層編號為 j 的杯子流下來的香檳單位
,那麼 f(0,0) = poured,且 f(i,j) = (f(i-1, j)-1)/2 + (f(i-1, j-1)-1)/2。
(如果f(i,j)-1 < 0 取0)
2.有遞迴關係式之後就可以直接套遞迴求解了,但是遞迴過程中有需多重複計算,所以
我們可以對函數作 memoization 記錄已經算過的值。
3.因為題目是要求杯子裡的容量,所以我們取 MIN(f(i,j), 1) 即可。
Java Code:
作者: wwndbk (黑人問號)   2023-09-24 16:58:00
大師
作者: Rushia (みけねこ的鼻屎)   2023-09-24 17:00:00
我看別人都用模擬的 我又想iwin了

Links booklink

Contact Us: admin [ a t ] ucptt.com