backtracking solution similar to generating parenthesis (5ms)


  • 1
    K
    public List<String> readBinaryWatch(int num) {
        List<String> result = new ArrayList<>();
        if(num==0){
            result.add("0:00");
            return result;    
        }  
        readBinaryWatch(result,num,0,0,"");
        return result;
    }
    
    private void readBinaryWatch(List<String> result,int num,int one,int zero, String str){
        if(one==num){
            StringBuilder stbr = new StringBuilder(str);
            while(stbr.length()<10) stbr.append("0");
            
            int hours = Integer.parseInt(stbr.substring(0,4), 2);
            if(hours>11) return;
            
            int mins = Integer.parseInt(stbr.substring(4), 2);
            if(mins>59) return;
            
            String toAdd =  hours + ":" + (mins>9?mins:"0"+mins); 
            result.add(toAdd);
            return;
        }
        if(one<num){
            readBinaryWatch(result,num,one+1,zero,str+"1");
        }
        if(zero<10-num){
            readBinaryWatch(result,num,one,zero+1,str+"0");
        }
    }

Log in to reply
 

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