799. Champagne Tower

70 阅读1分钟

image.png

image.png

方法

keep track of the total amount of champagne that flows through a glass. For example, if poured = 10 cups are poured at the top, then the total flow-through of the top glass is 10; the total flow-through of each glass in the second row is 4.5, and so on.

Algorithm

In general, if a glass has flow-through X, then Q = (X - 1.0) / 2.0 quantity of champagne will equally flow left and right.

class Solution {
    public double champagneTower(int poured, int query_row, int query_glass) {
        double[][] flow = new double[query_row + 2][query_row + 2];
        flow[0][0] = (double) poured;
        // must be <=, so above array should be + 2
        for (int i = 0; i <= query_row; i++) {
            for (int j = 0; j <= query_glass; j++) {
                double stream = (flow[i][j] - 1) / 2.0;
                if (stream > 0) {
                    flow[i + 1][j] += stream;
                    flow[i + 1][j + 1] += stream;
                }
            }
        }
        return Math.min(1.0, flow[query_row][query_glass]);
    }
}