https://leetcode.com/problems/champagne-tower/description/
非常好的题。开始想的时候一直是在想整个过程,感觉好复杂,甚至都想着模拟了因为100层数目大小还好。
看了 https://leetcode.com/problems/champagne-tower/discuss/118660/20ms-C++-Easy-understand-solution
明白了,递推即可
class Solution {
public:
double champagneTower(int poured, int query_row, int query_glass) {
if (poured == 0) return 0;
double dp[101][101];
dp[0][0] = poured;
for (int i = 1; i < 101; i++ ) {
for (int j = 0; j <= i; j++) {
dp[i][j] = 0.0;
if (j != i) {
if (dp[i-1][j] >= 1)dp[i][j] += (dp[i-1][j] - 1.0) / 2.0;
} else {
if (dp[i-1][j-1] >= 1)dp[i][j] += (dp[i-1][j-1] - 1.0) / 2.0;
}
if (j && j != i) {
if (dp[i-1][j-1] >= 1)dp[i][j] += (dp[i-1][j-1] - 1.0) / 2.0;
}
}
}
return min(dp[query_row][query_glass], 1.0);
}
};
class Solution {
public:
double champagneTower(int poured, int query_row, int query_glass) {
double result[101][101] = {0.0};
result[0][0] = poured;
for (int i = 0; i < 100; i++) {
for (int j = 0; j <= i; j++) {
if (result[i][j] >= 1) {
result[i + 1][j] += (result[i][j] - 1) / 2.0;
result[i + 1][j + 1] += (result[i][j] - 1) / 2.0;
result[i][j] = 1;
}
}
}
return result[query_row][query_glass];
}
};