leetcode-401. 二進制手錶

二進制手錶頂部有 4 個 LED 代表小時(0-11),底部的 6 個 LED 代表分鐘(0-59)。

每個 LED 代表一個 0 或 1,最低位在右側。

例如,上面的二進制手錶讀取 “3:25”。

給定一個非負整數 n 代表當前 LED 亮着的數量,返回所有可能的時間。

案例:

輸入: n = 1
返回: ["1:00", "2:00", "4:00", "8:00", "0:01", "0:02", "0:04", "0:08", "0:16", "0:32"]
 

注意事項:

輸出的順序沒有要求。
小時不會以零開頭,比如 “01:00” 是不允許的,應爲 “1:00”。
分鐘必須由兩位數組成,可能會以零開頭,比如 “10:2” 是無效的,應爲 “10:02”。

解法1遍歷可能出現的情況

class Solution {
    public List<String> readBinaryWatch(int num) {
        List<String> res = new ArrayList<>();
        for(int i = 0;i < 12;i++){
            for(int j = 0;j < 60;j++){
                if(count(i) + count(j) == num){
                    if(j < 10){
                        res.add(i+":0"+ j);
                    }else{
                        res.add(i+":"+ j);
                    }
                }
            }
        }
        return res;
    }
    
    public int count(int num){
        int res = 0;
        while(num != 0){
            num = num & (num - 1);
            res++;
        }
        return res;
    }
}

解法2:dfs

class Solution {
    int[] clock = {8, 4, 2, 1, 32, 16, 8, 4, 2, 1};
    int[] book = new int[10];
    List<String> res = new ArrayList<>();
    
    public List<String> readBinaryWatch(int num) {
        dfs(num, 0);
        return res;
    }
    
    public void dfs(int num,int cur){
        if(num == 0){
            int hour = 0,minute = 0;
            for(int i = 0;i < 4;i++){
                hour += book[i] * clock[i];
            }
            for(int i = 4;i < 10;i++){
                minute += book[i] * clock[i];
            }
            if(hour < 12 && minute < 60){
                res.add(String.format("%d:%02d", hour, minute));
            }
            return;
        }else{
            for(int i = cur;i < 10;i++){
                if(book[i] == 0){
                    book[i] = 1;
                    dfs(num - 1,i + 1);
                    book[i] = 0;
                }
            }
        }
    }
    
}

 

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章