401. Binary Watch


做题历程:

  1. 2016/Oct/20, 本题是第一次做,本次耗时45分钟独立解出

确实好久没有大量刷题了,导致刷题功力大降。。。本题只是道Easy题。。。。其实思路很快就有了,就是用DFS,不过本题需要加一点变化,就是要把用bit表示的时间转化为真正的时间。。就是这个搞了我好久,一大堆case开始没有考虑到。。。按理说这个级别的题,即便是第一次做,也应该5分钟内想好思路,20分钟内写出无bug的解才行。。。。太菜了。。

上代码:

class Solution {
public:
    vector<string> readBinaryWatch(int num) {
        dfs(num, 0, "");
        return tmp_res;
    }
private:
    vector<string> tmp_res;
    void dfs(int num, int index, string s) {
        if (s.length() == num) {
            string final_s = translate(s);
            if (final_s != "") {
                tmp_res.push_back(final_s);
            }
            return;
        }
        for (int i = index; i <= 10 - (num - s.length()); ++i) {
            dfs(num, i + 1, s + to_string(i));
        }
    }

    string translate(string str) {
        string res = "";
        int hour = 0;
        int minute = 0;
        for (int j = 0; j < str.length(); ++j) {
            if (str[j] < '4') {
                hour += pow(2, (3 - (str[j] - '0')));
            }
            else {
                minute += pow(2, (9 - (str[j] - '0')));
            }
        }
        if (hour < 12 && minute < 60) {
            res = to_string(hour) + ":";
            if (minute < 10) {
                res = res + "0" + to_string(minute);
            }
            else {
                res = res + to_string(minute);
            }
        }
        return res;

    }
};

results matching ""

    No results matching ""