작심삼일

[LeetCode] 799 | Champagne Tower | Python 본문

스터디/코테

[LeetCode] 799 | Champagne Tower | Python

yun_s 2022. 3. 4. 10:14
728x90
반응형

문제 링크: https://leetcode.com/problems/champagne-tower/


문제

We stack glasses in a pyramid, where the first row has 1 glass, the second row has 2 glasses, and so on until the $100^{th}$ row.  Each glass holds one cup of champagne.

Then, some champagne is poured into the first glass at the top.  When the topmost glass is full, any excess liquid poured will fall equally to the glass immediately to the left and right of it.  When those glasses become full, any excess champagne will fall equally to the left and right of those glasses, and so on.  (A glass at the bottom row has its excess champagne fall on the floor.)

For example, after one cup of champagne is poured, the top most glass is full.  After two cups of champagne are poured, the two glasses on the second row are half full.  After three cups of champagne are poured, those two cups become full - there are 3 full glasses total now.  After four cups of champagne are poured, the third row has the middle glass half full, and the two outside glasses are a quarter full, as pictured below.

Now after pouring some non-negative integer cups of champagne, return how full the $j^{th}$ glass in the $i^{th}$ row is (both i and j are 0-indexed.)


조건

  • 0 <= poured <= $10^9$
  • 0 <= query_glass <= query_row < 100

내 풀이

샴페인을 부으면 [i][j]번째 밑의 두 잔([i+1][j], [i+1][j+1])에는 [i][j]에 가득 담길 1잔 빼고 나머지가 흘러가게 된다.

이를 이용해 DP로 푼다.


코드

class Solution:
    def champagneTower(self, poured: int, query_row: int, query_glass: int) -> float:
        champ = [[0 for _ in range(101)] for _ in range(101)]
        champ[0][0] = poured
        
        for i in range(100):
            for j in range(i+1):
                if champ[i][j] >= 1:
                    champ[i+1][j] += ((champ[i][j]-1) / 2)
                    champ[i+1][j+1] += ((champ[i][j]-1) / 2)
                    champ[i][j] = 1
        
        return champ[query_row][query_glass]
728x90
반응형
Comments