博客
关于我
强烈建议你试试无所不能的chatGPT,快点击我
Leetcode: Binary Watch
阅读量:6817 次
发布时间:2019-06-26

本文共 2505 字,大约阅读时间需要 8 分钟。

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 = 1Return: ["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".
 

Solution 1: Bit Manipulation

use   Integer.bitCount()

1 public class Solution { 2     public List
readBinaryWatch(int num) { 3 List
res = new ArrayList
(); 4 for (int i=0; i<12; i++) { 5 for (int j=0; j<60; j++) { 6 if (Integer.bitCount(i) + Integer.bitCount(j) == num) { 7 String str1 = Integer.toString(i); 8 String str2 = Integer.toString(j); 9 res.add(str1 + ":" + (j<10? "0"+str2 : str2));10 }11 }12 }13 return res;14 }15 }

 

Solution 2: Backtracking, 非常精妙之处在于用了两个数组来帮助generate digit(例如:1011 -> 11)

1 public class Solution { 2     public List
readBinaryWatch(int num) { 3 int[] nums1 = new int[]{8, 4, 2, 1}, nums2 = new int[]{32, 16, 8, 4, 2, 1}; 4 List
res = new ArrayList
(); 5 for (int i=0; i<=num; i++) { 6 List
hours = getTime(nums1, i, 12); 7 List
minutes = getTime(nums2, num-i, 60); 8 for (int hour : hours) { 9 for (int minute : minutes) {10 res.add(hour + ":" + (minute<10? "0"+minute : minute));11 }12 }13 }14 return res;15 }16 17 public List
getTime(int[] nums, int count, int limit) {18 List
res = new ArrayList
();19 getTimeHelper(res, count, 0, 0, nums, limit);20 return res;21 }22 23 public void getTimeHelper(List
res, int count, int pos, int sum, int[] nums, int limit) {24 if (count == 0) {25 if (sum < limit) 26 res.add(sum);27 return;28 }29 for (int i=pos; i

 

转载地址:http://qwdzl.baihongyu.com/

你可能感兴趣的文章
linux资源分配Cgroup用法
查看>>
圆包含最多点问题
查看>>
Windows 8.1 发布了一个称为“Defender”的新模块
查看>>
浅析apache调优
查看>>
我的友情链接
查看>>
【Linux】如何正确安装Tomcat
查看>>
010-电脑软件安装手册-20190418
查看>>
linux学习笔记四(shell编程二)
查看>>
Hbase Shell 基础和常用命令
查看>>
数据结构和算法
查看>>
Linux_haproxy(3)v1.0
查看>>
Linux HA Cluster高可用集群之HeartBeat2
查看>>
C#中使用GetCursorPos获取屏幕坐标
查看>>
我的友情链接
查看>>
flume bucketpath的bug一例
查看>>
2017八款最佳反勒索软件工具
查看>>
Cache Buffers LRU Chain 闩锁竞争
查看>>
oracle系统用户详解
查看>>
从优化业务流程谈信息化管理
查看>>
Android系统编译系统分析大全(二)
查看>>