401. Binary Watch -Easy

Question

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.

Given a non-negative integer n which represents the number of LEDs that are currently on, return all possible times the watch could represent.

question

the above binary watch reads “3:25”.

一个二进制表有两排灯,上面一排的4盏代表0-11小时,下面一排的6盏代表0-59分钟。每个LED灯。每个LED灯的表现形式为1或0,最右侧代表最低位。现在给出一个非负整数n,它代表当前亮着的LED灯的个数,返回所有可能的表的时间。

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”]

Solution

  • 回溯解。我们只需要遍历n盏亮着的灯的所有组合,并且将小时 H < 12 且 分钟 M < 60 的组合保存下来即可。

    public class Solution {
        public List<String> readBinaryWatch(int num) {
            List<String> res = new ArrayList<>();
            backtracking(0, num, new boolean[10], res);
            return res;
        }
    
        /**
         * 思路:利用回溯遍历所有组合,只取小于H < 12小时且M < 59分钟的组合添加到res返回
         * @param start:从第以start为索引的灯开始亮
         * @param num:还需要亮的灯数
         * @param choose:表示10盏灯的亮暗情况(true代表亮,false代表暗)
         * @param res:返回列表结果
         */
        public void backtracking(int start, int num, boolean[] choose, List<String> res){
            // 10盏灯的代表数值(前4个代表小时,后6个代表分钟)
            int[] selectable = new int[]{1, 2, 4, 8, 1, 2, 4, 8, 16, 32};
            int hh = 0, mm = 0;
    
            // 如果已经点亮完所需的盏数,那么统计当前的H和M
            if(num == 0){
                for(int i = 0; i < 10; i++){
                    if(choose[i]){
                        if(i < 4) hh += selectable[i];
                        else mm += selectable[i];
                    }
                }
                // 只取 H < 12 且 M < 60 的组合
                if(hh < 12 && mm < 60){
                    if(mm < 10) res.add(hh + ":0" + mm);
                    else res.add(hh + ":" + mm);
                }
            }
    
            // 每次从start:10中选择一盏灯点亮
            for(int i = start; i < 10; i++){
                choose[i] = true;
                backtracking(i + 1, num - 1, choose, res);
                choose[i] = false;
            }
        }
    }
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值