recursive solution


  • 0
    M

    Get the all the permutations given num.

    class Solution {
        void getHour(vector<string> &ans, int hour, vector<int> &hours, int ind, int h) {
            if (hour > 11)
                return;
            if (h == 0) {
                ans.push_back(to_string(hour));
                return;
            }
            if (ind >= hours.size() || h < 0)
                return;
                
            getHour(ans, hour+hours[ind], hours, ind+1, h-1);
            getHour(ans, hour, hours, ind+1, h);
        }
        
        void getMinute(vector<string> &ans, int minute, vector<int> &minutes, int ind, int m) {
            if (minute > 59)
                return;
            if (m == 0) {
                if (minute < 10)
                    ans.push_back('0' + to_string(minute));
                else
                    ans.push_back(to_string(minute));
                return;
            }
            if (ind >= minutes.size() || m < 0)
                return;
                
            getMinute(ans, minute+minutes[ind], minutes, ind+1, m-1);
            getMinute(ans, minute, minutes, ind+1, m);
        }
        
    public:
        vector<string> readBinaryWatch(int num) {
            vector<string> ans;
            int a[] = {1, 2, 4, 8};
            int b[] = {1, 2, 4, 8, 16, 32};
            vector<int> hours(a, a+4);
            vector<int> minutes(b, b+6);
            
            for (int i=0; i<5 && i<=num; i++) {
                int j = num-i;
                if (j>=0 && j<7) {
                    vector<string> tmp1, tmp2;
                    getHour(tmp1, 0, hours, 0, i);
                    getMinute(tmp2, 0, minutes, 0, j);
                    for (int m=0; m<tmp1.size(); m++) {
                        for (int n=0; n<tmp2.size(); n++) {
                            ans.push_back(tmp1[m] + ':' + tmp2[n]);
                        }
                    }
                }
            }
            return ans;
        }
    };
    

Log in to reply
 

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