Backtracking is overkilling here. Just use bitset. 0ms C++


  • 0
    C

    [0-1024) represents all possible binary cases(2 to the power of 10) for this question.
    See post below.


  • 3
    C

    An alternative is to understand that 4 bits represent all possible hours [0,12), 6 bits represent all possible minutes [0,59). We just go through all possible combination.

    vector<string> readBinaryWatch(int num) {
        vector<string> ret;
        for (int i = 0; i <12 ; ++i) {
            bitset<4>h((size_t) i);
            for (int j = 0; j <60 ; ++j) {
                bitset<6>m((size_t)j);
                if (h.count()+m.count()==num)ret.push_back(to_string(i) + (j < 10 ? ":0" : ":") + to_string(j));
            }
        }
        return ret;
    }

Log in to reply
 

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.