C++ solution use STL permutation


  • 0
    W
    class Solution {
    public:
    	vector<string> readBinaryWatch(int num) {
    		const size_t N = 10;
    		vector<int> selectors(N, 0);
    		for (int i = 0; i < num; ++i) selectors[i] = 1;
    		vector<int> values = { 8, 4, 2, 1, 32, 16, 8, 4, 2, 1 };
    
    		vector<string> res;
    		do {
    			int hour = 0;
    			int minute = 0;
    			for (size_t i = 0; i < N; ++i) {
    				if (selectors[i]) {
    					if (i >= 0 && i <= 3) hour += values[i];
    					else minute += values[i];
    				}
    			}
    			if (hour >= 0 && hour <= 11 && minute >= 0 && minute <= 59) {
    				char buf[16] = { 0 };
    				snprintf(buf, 16, "%d:%02d", hour, minute);
    				res.push_back(buf);
    			}
    		} while (prev_permutation(selectors.begin(), selectors.end()));
    		return res;
    	}
    };
    

Log in to reply
 

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