leetcode_[python/java/javascript/C++]_401_Binary Watch(二進制手錶)

題目鏈接
【題目】
A binary watch has 4 LEDs on the top which represent the hours (0-11), and the 6 LEDs on the bottom represent the minutes (0-59).
Each LED represents a zero or one, with the least significant bit on the right.
這裏寫圖片描述
For example, the above binary watch reads “3:25”.
Given a non-negative integer n which represents the number of LEDs that are currently on, return all possible times the watch could represent.
Example:
Input: n = 1
Return: [“1:00”, “2:00”, “4:00”, “8:00”, “0:01”, “0:02”, “0:04”, “0:08”, “0:16”, “0:32”]

Note:
The order of output does not matter.
The hour must not contain a leading zero, for example “01:00” is not valid, it should be “1:00”.
The minute must be consist of two digits and may contain a leading zero, for example “10:2” is not valid, it should be “10:02”.


【分析】
有一個表是用二進制表示
4位表示小時
6位表示分鐘
亮起來的地方表示1,反之則是0.
如果這個表一共亮了n個燈,問可能有多少可能的時間組合
很顯然只是一種排列組合循環查找的問題:


下面分享不同語言的寫法哈哈


1 C++
首先貼一個我大一寫的代碼,智障寫法:

class Solution {
public:
    int read_int(int pos1,int pos2 = 10,int pos3 = 10){
    int temp = 0;
    if(pos1 == 10){
        return 0;
    }
    else if(pos2 == 10 && pos3 == 10){
        temp = pow(2,pos1);
    }
    else if(pos2!=10 && pos3 == 10){
        temp = pow(2,pos1)+pow(2,pos2);
    }
    else{
        temp = pow(2,pos1)+pow(2,pos2)+pow(2,pos3);
    }
    return temp;

}
string read_string(int flag,bool rev,int pos1,int pos2=10, int pos3=10){
    string s="";
    int temp = 0;
    temp = read_int(pos1,pos2,pos3);
    if(rev == false){
        temp = temp;
    }
    else{
        if(flag == 0){
            temp = 15-temp;
        }
        else{
            temp = 63-temp;
        }
    }
    if(temp>9){
        s += char(temp/10+'0');
        s += char(temp%10+'0');
    }
    else{
        if(flag == 1) 
            s+=char('0');
        s += char(temp + '0');
    }
    return s;
}
struct P{
    int a0,a1,a2;
    P(int b1,int b2,int b3){
        a0 = b1;
        a1 = b2;
        a2 = b3;
    }
};
vector<string> readBinaryWatch(int num) {

    vector<string> v_s;
    if(num==0) v_s.push_back("0:00");
    else{
        int i = num;
        int j = 0;
        vector<P> a[3],b[4];
        a[0].push_back(P(10,10,10));

        a[1].push_back(P(0,10,10));
        a[1].push_back(P(1,10,10));
        a[1].push_back(P(2,10,10));

        a[2].push_back(P(0,1,10));
        a[2].push_back(P(1,2,10));
        a[2].push_back(P(2,3,10));
        a[2].push_back(P(0,2,10));
        a[2].push_back(P(1,3,10));

        b[0].push_back(P(10,10,10));

        b[1].push_back(P(0,10,10));
        b[1].push_back(P(1,10,10));
        b[1].push_back(P(2,10,10));
        b[1].push_back(P(3,10,10));
        b[1].push_back(P(4,10,10));
        b[1].push_back(P(5,10,10));
        b[2].push_back(P(0,1,10));
        b[2].push_back(P(1,2,10));
        b[2].push_back(P(2,3,10));
        b[2].push_back(P(3,4,10));
        b[2].push_back(P(4,5,10));
        b[2].push_back(P(0,2,10));
        b[2].push_back(P(1,3,10));
        b[2].push_back(P(2,4,10));
        b[2].push_back(P(3,5,10));
        b[2].push_back(P(0,3,10));
        b[2].push_back(P(1,4,10));
        b[2].push_back(P(2,5,10));
        b[2].push_back(P(0,4,10));
        b[2].push_back(P(1,5,10));
        b[2].push_back(P(0,5,10));
        b[3].push_back(P(0,1,2));
        b[3].push_back(P(1,2,3));
        b[3].push_back(P(2,3,4));
        b[3].push_back(P(3,4,5));
        b[3].push_back(P(0,1,3));
        b[3].push_back(P(0,1,4));
        b[3].push_back(P(0,1,5));
        b[3].push_back(P(1,2,4));
        b[3].push_back(P(1,2,5));
        b[3].push_back(P(0,2,3));
        b[3].push_back(P(2,3,5));
        b[3].push_back(P(0,3,4));
        b[3].push_back(P(1,3,4));
        b[3].push_back(P(0,4,5));
        b[3].push_back(P(1,4,5));
        b[3].push_back(P(2,4,5));
        b[3].push_back(P(0,2,4));
        b[3].push_back(P(0,2,5));
        b[3].push_back(P(0,3,5));
        b[3].push_back(P(1,3,5));
         while(i>6){
            i--;
            j++;
        }
        while(j<=4&&j>=0&&i<=6&&i>=0){
            int len1 = 0,len2 = 0;
            string s1[20],s2[20];

            if(j<=2){
                for(int h = 0;h < a[j].size();h++){
                    s1[h] = read_string(0,false,a[j][h].a0,a[j][h].a1,a[j][h].a2);
                    len1 = h;
                }
            }
            else if(j>2){
                for(int h = 0;h<a[4-j].size();h++){
                    s1[h] = read_string(0,true,a[4-j][h].a0,a[4-j][h].a1,a[4-j][h].a2);
                    len1 = h;
                }
            }
            if(i<=3){
                for(int g = 0;g < b[i].size();g ++){
                    s2[g]=read_string(1,false,b[i][g].a0,b[i][g].a1,b[i][g].a2);
                    len2 = g;
                }
            }
            else if(i>3){
                for(int g = 0;g < b[6-i].size();g ++){
                    s2[g]=read_string(1,true,b[6-i][g].a0,b[6-i][g].a1,b[6-i][g].a2);
                    len2 = g;
                }

            }
            len1++;
            len2++;
            for(int k1 = 0;k1<len1;k1++){
                for(int k2 = 0;k2<len2;k2++){
                    string s = "";
                    if(s2[k2].size() == 2 && s2[k2][0] == '6'){
                        continue;
                    }
                    if(s1[k1].size() == 2 && s1[k1][1] >= '2'){
                        continue;
                    }

                    s = s1[k1] + ":" + s2[k2];

                    v_s.push_back(s);
                }
            }
            j++;
            i--;
        }
    }
    return v_s;


}
};

現在看着就很好笑,不過自然就是這麼改變進步的吧
這道題可以用深度搜索的方法寫,網上也是其他做法
分享一個簡短的利用內置類與函數的解法,bitset是一個內置類,可以將其他進制的數轉換爲二進制,和一個count函數,來計算1的個數

class Solution {
public:
    vector<string> readBinaryWatch(int num)
    {
        vector<string> ans;
        for(int i = 0; i < 12; i ++ )
        {
            for (int j = 0 ; j < 60 ; j ++ )
            {
                if(bitset<10>((i<<6)+j).count() == num)
                {
                    ans.push_back(to_string(i) + (j<10?":0":":") + to_string(j));
                }
            }
        }
        return ans;
    }
};

很強!


2 python:
當然想到排列組合,自然想到python的itertools裏面的兩個函數,permutations和combinations
前者有區別先後,後者沒有,這道題中由於我們並不在意(1,2)和(2,1)的區別,所以自然用combinations()

class Solution(object):
    def readBinaryWatch(self, num):
        """
        :type num: int
        :rtype: List[str]
        """
        from itertools import combinations
        def get_int_from_LED(n,k):
            value = [2**i for i in range(k)]
            comb = combinations(value,n)
            ans = []
            for item in comb:
                ans += [sum(item)]
            return ans
        ans = []
        for i in range(min(5,num+1)):
            j = num - i
            value4 = get_int_from_LED(i,4)
            value6 = get_int_from_LED(j,6)
            for v4 in value4:
                for v6 in value6:
                    if v4 < 12 and v6 < 60:
                        temp = str(v6) if v6 > 9 else "0" + str(v6)
                        ans.append(str(v4) + ":" + temp)
        return ans

同樣的python中也有二進制的內置函數,可以一行搞定:

def readBinaryWatch(self, num):
    return ['%d:%02d'.format(h,m) for m in range(60) for h in range(12) if (bin(h) + bin(m)).count('1') == num]

3 java:
下面的做法將所有情況列舉出來,循環求解結果,但是很快

public class Solution {
        String[][] hour = {{"0"}, 
                                   {"1", "2", "4", "8"},
                   {"3", "5", "6", "9", "10"},
                   {"7", "11"}};
        String[][] minute = {{"00"}, //1
                         {"01", "02", "04", "08", "16", "32"}, //6
                         {"03", "05", "06", "09", "10", "12", "17", "18", "20", "24", "33", "34", "36", "40", "48"}, //15
                         {"07", "11", "13", "14", "19", "21", "22", "25", "26", "28", "35", "37", "38", "41", "42", "44", "49", "50", "52", "56"}, //20
                         {"15", "23", "27", "29", "30", "39", "43", "45", "46", "51", "53", "54", "57", "58"}, //14
                         {"31", "47", "55", "59"}}; //4
    public List<String> readBinaryWatch(int num) {
        List<String> ret = new ArrayList();
        for (int i = 0; i <= 3 && i <= num; i++) {
            if (num - i <= 5) {
                for (String str1 : hour[i]) {
                    for (String str2 : minute[num - i]) {
                        ret.add(str1 + ":" + str2);
                    }
                }
            }
        }
        return ret;     
    }
}

是的,java也有二進制:

public List<String> readBinaryWatch(int num) {
    List<String> times = new ArrayList<>();
    for (int h=0; h<12; h++)
        for (int m=0; m<60; m++)
            if (Integer.bitCount(h * 64 + m) == num)
                times.add(String.format("%d:%02d", h, m));
    return times;        
}

4 javascript:
最後,分享一種js解法:

var readBinaryWatch = function(num) {
    var hour,
        minutes,
        numBits,
        result = [],
        hourFormat = "";

    for(hour = 0; hour <= 11; hour++){
        for(minutes = 0; minutes <= 59; minutes++){
            numBits = hour.toString(2).split(1).length - 1;
            numBits += minutes.toString(2).split(1).length - 1;
            if(numBits === num){
                hourFormat = hour.toString() + ":" + (minutes < 10? '0' + minutes.toString() : minutes.toString());
                result.push(hourFormat);
            }

        }
    }

    return result;
};
發佈了45 篇原創文章 · 獲贊 18 · 訪問量 7萬+
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章