LeetCode 799 JavaScript

pimkle發表於2019-04-12

思路

LeetCode 799 JavaScript
下述程式碼不要用字串處理會快很多 應該用矩陣的

程式碼

/**
 * @param {number} poured
 * @param {number} query_row
 * @param {number} query_glass
 * @return {number}
 */
var champagneTower = function(poured, query_row, query_glass) {
    // function queryWinePoured(r, g) {
    //     if (g > r) {
    //         return 0;
    //     } else if (r < 0 || g < 0) {
    //         return 0;
    //     } else if (g === 0 && r === 0) {
    //         return poured;
    //     } else {
    //         let left = queryWinePoured(r - 1, g - 1);
    //         let right = queryWinePoured(r - 1, g);
    //         return ((left > 1 ? left - 1 : 0) + (right > 1 ? right - 1 : 0)) / 2;
    //     }
    // }
    // return Math.min(queryWinePoured(query_row, query_glass), 1);
    function fillZero(num) {
        return num > 9 ? num + '' : '0' + num;
    }
    function countWinePoured(r, g) {
        if(r === 0 && g === 0) {
            return poured;
        } else if(r < 0 || g < 0) {
            return 0;
        } else {
            let left = saved[fillZero(r - 1) + fillZero(g - 1)];
            let right = saved[fillZero(r - 1) + fillZero(g)];
            return ((left - 1 > 0 ? left - 1 : 0) + (right - 1 > 0 ? right - 1 : 0)) / 2
        }
    }
    let r = 0;
    let saved = {};
    while(true) {
        let allRowZero = true;
        for(let g = 0; g <= r; ++g) {
            let result = countWinePoured(r, g);
            if(r === query_row && g === query_glass) {
                return Math.min(result, 1);
            }
            saved[fillZero(r) + fillZero(g)] = result;
            if(result > 0) {
                allRowZero = false;
            }
        }
        if(allRowZero) {
            return 0;
        }
        r ++;
    }
};
複製程式碼

相關文章