# LeetCode算法题-Binary Watch（Java实现）

### 01 看题和准备

• 输出顺序无关紧要。
• 小时不得包含前导零，例如“01:00”无效，应为“1:00”。
• 分钟必须由两位数组成，并且可能包含前导零，例如“10：2”无效，应为“10:02”。

### 02 第一种解法

public List<String> readBinaryWatch(int num) {
List<String> list = new ArrayList<String>();
for (int i=0; i<12; i++) {
for (int j=0; j<60; j++) {
if (Integer.bitCount(i)+Integer.bitCount(j) == num) {
if (j < 10) {
answer = i + ":0" + j;
} else {
answer = i + ":" + j;
}
}
}
}
return list;
}

### 03 第二种解法

public List<String> readBinaryWatch2(int num) {
List<String> list = new ArrayList<String>();
if (num == 0) {
return list;
}
if (num > 8) {
return list;
}
int[] temp = {8,4,2,1,32,16,8,4,2,1};
boolean[] index = new boolean[10];
helperFun(list, temp, index, num, 0);
return list;
}

void helperFun(List<String> list, int[] temp, boolean[] index, int num, int start){
if (num == 0) {
int hour = 0;
int minute = 0;
for (int k = 0; k < 10; k++) {
if (index[k] == true && k <= 3) {
hour += temp[k];
}
if (index[k] == true && k > 3) {
minute += temp[k];
}
}
if (hour >= 12 || minute >= 60) {
return;
} else {
if (minute < 10) {
answer = hour + ":0" + minute;
} else {
answer = hour + ":" + minute;
}
return;
}
}
for (int i = start; i < temp.length; i++) {
index[i] = true;
helperFun(list, temp, index, num - 1, i + 1);
index[i] = false;
}
}

### 04 第三种解法

private int[] all = {1,2,4,8,1,2,4,8,16,32};
List<String> list = new ArrayList<String>();
helperFun(list, num, 0, 0, 0);
return list;
}

void helperFun(List<String> list, int num, int hour, int minute, int index) {
if (hour > 11 || minute > 59) {
return;
}
if (num == 0) {
if (minute < 10) {
answer = hour + ":0" + minute;
} else {
answer = hour + ":" + minute;
}
}
for (int i=index; i<10; i++) {
if (i < 4) {
helperFun(list, num-1, hour+all[i], minute, i+1);
} else {
helperFun(list, num-1, hour, minute+all[i], i+1);
}
}
}

### 05 小结

posted @ 2018-12-29 08:37  程序员小川  阅读(...)  评论(...编辑  收藏