题目如下:
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 = 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".
public List<String> readBinaryWatch(int num) {
int hour[][] = {{0},{1,2,4,8},{3,5,6,9,10},{7,11}};
int minutes[][] = {{0},{1,2,4,8,16,32},{3,5,6,9,10,12,17,18,20,24,33,34,36,40,48},
{7,11,13,14,19,21,22,25,26,28,35,37,38,41,42,44,49,50,52,56},
{15,54,23,27,29,30,39,51,43,45,46,57,58,53},{31,47,55,59}
};
List<String> result = new LinkedList<String>();
int boundary = num>=4?4:num+1;
for(int i=0;i<boundary;i++){
int index = num-i;
if(index>5) continue;
for(int j=0;j<hour[i].length;j++){
for(int k=0;k<minutes[index].length;k++){
String minute;
if(minutes[index][k]/10==0){
minute = "0"+minutes[index][k];
}else{
minute = ""+minutes[index][k];
}
String temp = hour[i][j]+":"+minute;
result.add(temp);
}
}
}
return result;
}
评论区里这个方法好屌,让我感觉自己宛如一个智障,代码如下:
public List<String> readBinaryWatch(int num) {
List<String> 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;
}
好在这个评论区的方法有一个缺点,就是速度比较慢......要不然真是碾压啊。
评论区中还有一种使用backtracking的方法,地址在这里:https://discuss.leetcode.com/topic/59494/3ms-java-solution-using-backtracking-and-idea-of-permutation-and-combination。感兴趣的可以自己看一下...