Java 3ms Solution using backtracking


  • 0
    K
    public List<String> readBinaryWatch(int num) {
        List<String> result = new ArrayList<>();
        help(num, 0, 0, 0, result);
        return result;
    }
    
    private void help(int num, int pos, int hour, int minute, List<String> result) {
        if (hour > 11 || minute > 59)
            return;
        if (num == 0) {
            result.add("" + hour + ":" + (minute > 9 ? minute : "0" + minute));
            return;
        }
        for (int i = pos; i < 10; i++) {
            if (i <= 3) {
                help(num-1, i+1, hour + (1 << (3 - i)), minute, result);
            } else {
                help(num-1, i+1, hour, minute + (1 << (9 - i)), result);
            }
        }
    }

Log in to reply
 

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