二进制手表算法(Java)

时间:2016-10-16 07:20:38

标签: java algorithm

我正在尝试编写一种算法,该算法返回二进制手表上的许多灯可能代表的所有可能的时间值。

详细信息可以在这里找到: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);
        }
    }

}}

我的解决方案似乎在一些测试用例中失败了,我似乎无法弄清楚原因。建议?

1 个答案:

答案 0 :(得分:1)

你总是选择花时间[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);
    }
}