my 0ms c++ straightforward soulution using combination


  • 0
    C
    class Solution {
    public:
    	void pushres(string& s, vector<string>& res){
    		int hour = 0, minite = 0;
    		for (int i = 0; i < s.size(); i++){
    			if (s[i] == '1'){
    				if (i < 4)
    					hour += valuetable[i];
    				else
    					minite += valuetable[i];
    			}
    		}
    		if (hour > 11 || minite > 59)
    			return;
    		string tmp;
    		tmp += to_string(hour);
    		tmp.push_back(':');
    		if (minite < 10)
    			tmp.push_back('0');
    		tmp += to_string(minite);
    		res.emplace_back(move(tmp));   //--------------
    		return;
    	}
    	void readBinaryWatchCore(string& s, int i, int k, vector<string>& res){
    		if (k <= 0){
    			pushres(s, res);
    			return;
    		}
    		if (nBits - i< k)
    			return;
    		s[i] = '1';
    		readBinaryWatchCore(s, i + 1, k - 1, res);
    		s[i] = '0';
    		readBinaryWatchCore(s, i + 1, k, res);
    		return;
    	}
    	vector<string> readBinaryWatch(int num) {
    		nBits = 10;
    		int base = 1;
    		vector<int> tmp(10, 0);
    		for (int i = 9; i >= 0; i--){
    			if (i == 3)
    				base = 1;
    			tmp[i] = base;
    			base <<= 1;
    		}
    		valuetable = move(tmp);
    		string s(10, '0');
    		vector<string> res;
    		readBinaryWatchCore(s, 0, num, res);
    		return res;
    	}
    private:
    	int nBits;
    	vector<int> valuetable;
    };
    

Log in to reply
 

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