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.
leetcode_[python/java/javascript/C++]_401_Binary Watch(二进制手表)_第1张图片
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

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;h4-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;k1for(int k2 = 0;k2string 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 readBinaryWatch(int num) {
        List 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 readBinaryWatch(int num) {
    List 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;
};

你可能感兴趣的:(&,C++)