【LeetCode Contest 143.】1103 1104 1105 1106

这次没迟到,但是惨败。

1103. Distribute Candies to People

给n个人分糖果,每一圈比前一次增加n个,问每个人能分到多少个。
前半个小时,一直试图推公式,最后发现while循环就过了。卒。

1104. Path In Zigzag Labelled Binary Tree

一棵二叉树,按照每层Zigzag的方式给节点标记,问从根节点到 label 节点的路径。
试图不建树,直接按照某种规律直接访问,未果,然后开始建树,可行,比完赛20分钟过了。卒。

1105. Filling Bookcase Shelves

书架宽度固定,按照给定顺序放书,书有高度和宽度,问放下所有的书的最低高度。
看题解。对每个i,把后边的 j~i 本书当做下一层的书,来计算前 i 本书的最低高度。

代码:

class Solution {
public:
    int minHeightShelves(vector<vector<int>>& books, int shelf_width) {
        int n = books.size();
        vector<int> dp(n+1, INT_MAX);
        dp[0] = 0;
        
        for (int i=1; i<=n; ++i) {
            int w = 0;
            int h = 0;
            for (int j=i; j>=1; --j) {
                w += books[j-1][0];
                if (w > shelf_width) break;
                h = max(h, books[j-1][1]);
                dp[i] = min(dp[i], dp[j-1]+h);
            }
        }
        return dp[n];
    }
};

1106. Parsing A Boolean Expression

解析字符串,只有 {’(’, ‘)’, ‘&’, ‘|’, ‘!’, ‘t’, ‘f’, ‘,’} 种字符,比赛的时候感觉和之前的一个解析字符串很相似,那个是用栈写的,而且很麻烦。
看题解,递归写的很简洁。觉得有点难。

代码:

class Solution {
public:
    bool parseBoolExpr(string expression) {
        int s = 0;
        bool ans = parse(expression, s); 
        return ans;
    }
    
    bool parse(const string& expression, int& s) {
        char ch = expression[s++];
        if (ch == 't') return true;
        else if (ch == 'f') return false;
        else if (ch == '!') {
            bool ans = !parse(expression, ++s);
            ++s;
            return ans;
        }
        bool is_and = (ch == '&');
        ++s;
        bool ans = is_and;
        while(true) {
            bool temp = parse(expression, s);
            if (is_and) ans &= temp;
            else ans |= temp;
            if (expression[s++] == ')') break;
        }
        return ans;
    }
};

猜你喜欢

转载自blog.csdn.net/iCode_girl/article/details/94554754