My recursive solution,0ms


  • 0
    X

    sorry l do not know the bitsetclass before the topic,so l write a recursive solution

    vector<string> readBinaryWatch(int num) {
    	vector<string> res;
    	for (int i = 0; i <= 4 && i <= num; ++i) {
    		if (num - i > 6) continue;
    		vector<int> hour, min;
    		int binary_num = 0;
    		readBinaryNum(4, i, binary_num, hour);
    		readBinaryNum(6, num - i, binary_num, min);
    		for (auto h : hour) {
    			if (h >= 12) continue;
    			for (auto m : min) {
    				if (m >= 60) continue;
    				res.push_back((h ? to_string(h) : "0") + (m > 9 ? ":" : ":0")+ (m ? to_string(m) : "0"));
    			}
    		}
    	}
            return res;
    }
    	
    void readBinaryNum(int bits, int ones, int num, vector<int> &ans) {
    	if (ones == 0) {
    		ans.push_back(num);
    		return;
    	}
    	if (bits == 0)
    		return;
    	for (int i = 0; i < bits; ++i) {
    		readBinaryNum(i, ones - 1, num | (1 << i), ans);
    	}
    }
    

Log in to reply
 

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