我正在尝试编写一种算法,返回所有可能的时间值,二进制 watch 上的许多灯可以表示。
整个问题的细节可以在这里找到:https://leetcode.com/problems/binary-watch/
public class Solution {
public List<String> readBinaryWatch(int num) {
List<String> result = new ArrayList<String>();
int[] time = new int[] {1, 2, 4, 8, 1, 2, 4, 8, 16, 32};
helper(result, time, num, 0, 0, 0);
return result;
}
public void helper(List<String> result, int[] time, int num, int start, int hour, int minute){
if (num == 0){
if (hour < 11 && minute < 59){
String x = "" + hour + ":";
if (minute < 10){x = x + "0";}
x = x + minute;
result.add(x);
}
} else {
for (int i = start; i < time.length; i++){
int h, m;
if (i >= 4){h = hour; m = minute + time[i];} else {h = hour + time[i]; m = minute;}
helper(result, time, num - 1, start + 1, h, m);
}
}
}}
我的解决方案似乎无法通过某些测试用例,而且我似乎无法弄清楚原因。有什么建议吗?
最佳答案
您总是选择花时间 [i],从而跳过选项。 另外,你为什么要使用? 要么选择花时间 [开始] 要么不 - 两个递归调用:
public void helper(List<String> result, int[] time, int num, int start, int hour, int minute){
if (start == time.length && num > 0)
return;
if (num == 0){
if (hour <= 12 && minute <= 59){
String x = "" + hour + ":";
if (minute < 10){x = x + "0";}
x = x + minute;
result.add(x);
}
} else {
helper(result, time, num, start + 1, hour, minute);
int h, m;
if (start >= 4){h = hour; m = minute + time[start];} else {h = hour + time[start]; m = minute;}
helper(result, time, num - 1, start + 1, h, m);
}
}
关于java - 二进制 watch 算法 (Java),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40067898/