JAVA backtracking solution


  • 0
    W

    '''
    public List<String> readBinaryWatch(int num) {
    boolean[] watch=new boolean[10];
    List<String> res=new ArrayList<String>();
    backtracking(num,res,watch,0);
    return res;
    }

    public void backtracking(int count,List<String> res,boolean[] watch,int index){
        if(index>9){
            if(count!=0) return;
        }
        if(count==0){
            int hour=0;
            int minute=0;
    
            for(int i=0;i<6;i++){
                if(watch[i]){
                    minute+=Math.pow(2,i);
                }
                if(minute>59){
                    return;
                }
            }
            for(int i=6;i<10;i++){
                if(watch[i]){
                    hour+=Math.pow(2,i-6);
                }
                if(hour>11){
                    return;
                }
            }
            String minutes="";
            if(minute<10){
                minutes="0"+minute;
            }else{
                minutes=""+minute;
            }
            res.add(hour+":"+minutes);
            return;
        }
        watch[index]=true;
        backtracking(count-1,res,watch,index+1);
        watch[index]=false;
        backtracking(count,res,watch,index+1);
    }

Log in to reply
 

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