401. Binary Watch -Easy
来源:互联网 发布:人民法院淘宝网 编辑:程序博客网 时间:2024/04/24 02:38
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.
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
- 401. Binary Watch -Easy
- 401.leetcode Binary Watch(easy)[递归回溯]
- 【Leetcode】401. Binary Watch
- 401. Binary Watch
- 401. Binary Watch
- [LeetCode]401. Binary Watch
- 401. Binary Watch
- 401. Binary Watch
- 401.Binary Watch
- 401. Binary Watch
- 401. Binary Watch
- LeetCode 401. Binary Watch
- [leetcode]401. Binary Watch
- 401. Binary Watch
- Leetcode 401. Binary Watch
- LeetCode 401. Binary Watch
- LeetCode 401. Binary Watch
- LeetCode 401. Binary Watch
- 【backtrack】dns信息收集
- 解决cin,cout速度过慢问题
- 《数学之美》第一章脑图:文字,数字与信息
- MyBatis快速入门(三) 动态SQL
- android打包提示checkreleasebuilds false
- 401. Binary Watch -Easy
- linux关于S权限和T权限的介绍
- 贪心——Kickstart 2017 practice Round #C
- JAVA全集-07-Java集合
- 【backtrack】路由信息收集
- 51 NOD 1012 最小公倍数LCM
- C++ 字符串分割 split
- asp.net core mvc剖析:处理管道构建
- 脱离文档流之 float 和 position:absolute的区别