c++ dps solution (bit manipulation)


  • 0
    B
        vector<string> readBinaryWatch(int num) {
            union {
                struct {
                    unsigned hours:4;
                    unsigned minutes:6;
                };
                unsigned all;
            } time {0};
    
            vector<string> result;
            function<void(int, int)> place = [&](int n, int ifrom) {
                if (n == 0) {
                    if (time.hours < 12 and time.minutes < 60) {
                        char buf[20];
                        sprintf(buf, "%d:%02d", time.hours, time.minutes);
                        result.push_back(string(buf));
                    }
                } else {
                    for (int i = ifrom; i < 10; ++i) {
                        if (!(time.all >> i & 1)) {
                            time.all |= 1 << i;
                            place(n - 1, i);
                            time.all &= ~(1 << i);
                        }
                    }
                }
            };
            place(num, 0);
            return result;
        }
    

    overkill as usual


Log in to reply
 

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