Easy to understand Java backtracking solution- only 3ms!!


  • 1
    D

    '''
    public class Solution {

    private int[] watch = {1, 2, 4, 8, 16, 32, -1, -2, -4, -8}; //negative values represent hour LEDs
    
    public List<String> readBinaryWatch(int num) {
        List<String> result = new ArrayList<String>();
        readBinaryWatch(num, 0, 0, 0, result);
        return result;
    }
    
    private void readBinaryWatch(int num, int index, int hr, int min, List<String> result) {
        //check bounds of hours and minutes
        if(hr < -11 || min > 59) return;
        if(num == 0) {
            StringBuilder time = new StringBuilder();
            time.append(Math.abs(hr));
            time.append(min<10?":0":":");
            time.append(min);
            result.add(time.toString());
            return;
        }
        for(int i=index; i < watch.length; i++) {
            if(watch[i] < 0) readBinaryWatch(num-1, i+1, hr + watch[i], min, result);
            else readBinaryWatch(num-1, i+1, hr, min + watch[i], result);
        }
    }
    

    }
    '''


Log in to reply
 

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