leetcode-第十四周

来源:互联网 发布:美国历史gdp数据统计 编辑:程序博客网 时间:2024/05/16 10:43

17. Letter Combinations of a Phone Number

/** * Time: O(4 ^ n) * Space: O(n) * 思路:深搜暴力求解 */class Solution {private:    void dfs(const string &digits, int pos, vector<string> &ret, string &current) {        const char* l[10] = { "", "", "abc", "def", "ghi", "jkl", "mno", "pqrs", "tuv", "wxyz" };        if (pos == digits.size()) { // 收敛条件            ret.push_back(current);            return;        }        int val = digits[pos] - '0';        for (int i = 0; i < strlen(l[val]); i++) { // 执行扩展动作            current.push_back(l[val][i]);            dfs(digits, pos + 1, ret, current);            current.pop_back();        }    }public:    vector<string> letterCombinations(string digits) {        vector<string> ret;        if (digits.empty()) return ret;        string current = "";        dfs(digits, 0, ret, current);        return ret;    }};

44. Wildcard Matching

/** * MLE思路:dp[i + 1][j + 1]表示s[0-i]和p[0-j]是否匹配 * 1. p[j] == '*', dp[i + 1][j], dp[i][j + 1] => dp[i + 1][j + 1] * 2. p[j] != '*', dp[i][j] => dp[i + 1][j + 1] *  * 思路二:滚动数组,用pre替代dp[i],cur替代dp[i + 1] * 1. p[j] == '*', cur[j], pre[j + 1] => cur[j + 1] * 2. p[j] != '*', pre[j] => cur[j + 1] */class Solution {private:    typedef vector<int> VI;    typedef vector<VI> VVI;    inline bool match(char a, char b) {        if ('?' == a || '?' == b) return true;        else return a == b;    }public:    bool isMatch(string s, string p) {        int sn = s.size(), pn = p.size();        // use one dimension for avoiding MLE        // NOTE THAT: only p can contain '*' and '?'        VI pre = VI(pn + 1, false);        pre[0] = true;        for (int j = 0; j < pn; j++) if (p[j] == '*') pre[j + 1] = pre[j];        for (int i = 0; i < sn; i++) {            VI cur = VI(pn + 1, false);            for (int j = 0; j < pn; j++) {                if (p[j] != '*') {                    if (match(s[i], p[j]))                        cur[j + 1] = pre[j];                } else {                    cur[j + 1] = cur[j] || pre[j + 1];                }            }            pre = cur;        }        bool ans = pre[pn];        return ans;    }};

401. Binary Watch

class Solution {private:    int cnt(int a) {        int ret = 0;        for (; a; a = a & (a - 1)) ret++;        return ret;    }public:    vector<string> readBinaryWatch(int num) {        vector<string> ret;        for (int h = 0; h < 12; h++) {            for (int m = 0; m < 60; m++) {                if (cnt(h) + cnt(m) == num) {                    string tmp = to_string(h) + ":";                    tmp += m < 10 ? "0" + to_string(m): to_string(m);                    ret.push_back(tmp);                }            }        }        return ret;    }};