Easy to understand backtracking solution


  • 0
    F
    private int[] hour = {1, 2, 4, 8};
    private int[] minute = {1, 2, 4, 8, 16, 32};
    public List<String> readBinaryWatch(int num) {
        List<String> result = new ArrayList<>();
        helper(num, result, 0, 0, 0, 0);
        return result;
    }
    
    public void helper(int num, List<String> result, int h, int m, int pos1, int pos2) {
        if (num == 0) {
            if (m <= 9) {
                result.add(h + ":0" + m);
            } else {
                result.add(h + ":" + m);
            }
        }
        int i = pos1, j = pos2;
        for (; i < 4; i++) {
            if (h + hour[i] < 12) {
                h += hour[i];
                helper(num - 1, result, h, m, i + 1, j);
                h -= hour[i];
            } else {
                break;
            }
        }
        
        for (; j < 6; j++) {
            if (m + minute[j] < 60) {
                m += minute[j];
                helper(num - 1, result, h, m, i, j + 1);
                m -= minute[j];
            } else {
                break;
            }
        }
    }

  • 0
    Y
    This post is deleted!

  • 0
    F

    @yixuanwang.start It should be break, I forgot to change it.


Log in to reply
 

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.