401 Binary Watch
Problem:
Input: n = 1
Return: ["1:00", "2:00", "4:00", "8:00", "0:01", "0:02", "0:04", "0:08", "0:16", "0:32"]Solutions:
public class Solution {
public List<String> readBinaryWatch(int num) {
boolean[] watch = new boolean[10];
int[] vals = new int[]{8, 4, 2, 1, 32, 16, 8, 4, 2, 1};
List<String> result = new LinkedList<String>();
process(num, 0, watch, vals, result);
return result;
}
private void process(int left, int start, boolean[] watch, int[] vals, List<String> result) {
if (left == 0) {
int hour = 0;
for (int i = 0; i < 4; i ++) {
if (watch[i] == true) {
hour += vals[i];
}
}
if (hour >= 12) {
return;
}
int min = 0;
for (int i = 4; i < 10; i ++) {
if (watch[i] == true) {
min += vals[i];
}
}
if (min >= 60) {
return;
}
String time = hour + ":";
if (min < 10) {
time += "0";
}
time +=min;
result.add(0, time);
return;
}
for (int i = start; i< watch.length; i ++) {
watch[i] = true;
process(left - 1, i + 1, watch, vals, result);
watch[i] = false;
}
}
}Last updated
