Javascript recursive solution


  • 0
    Y

    being an non-programmer, here is what I did, please comment...

    It is based on using f(n) to derive f(n+1)

    for example with hour [1,2,4,8]
    hour (n=1) is [1,2,4,8]
    hour (n=2) is 1 combine with [2,4,8] n=1 solution, 2 combine with [4,8] n=1 solution, 4 combine with [8] n=1 solution..........
    same as hour n=3, minute n=2,3,4,5.......

    var help=function(nums,n,max){
        var output=[];
        var len0=nums.length;
        if(n===0){
            return [0];
        
        }
        if(n===1){
            return nums;
        }
        var modnums=[];
        for(var a0=0;a0<len0;a0++){
            modnums[a0]=nums[a0];
        }
        
        for(var a1=0;a1<len0-n+1;a1++){
            modnums.shift();
            var item1=help(modnums,n-1,max);
            var len1=item1.length;
            for(var a2=0;a2<len1;a2++){
                var item2=nums[a1]+item1[a2];
                if(item2<=max){
                    output.push(item2);
                }
            }
            
        }
        return output;
        
    };
    
    
    
    var readBinaryWatch = function(num) {
    
        var output=[];
        var hnum=[1,2,4,8];
        var mnum=[1,2,4,8,16,32];
        var hmax=11;
        var mmax=59;
        
        if(num>8){
            return [];
        }
                
        for(var a1=0;a1<=num;a1++){    
            var houritem=help(hnum,a1,hmax);
            var minitem=help(mnum,num-a1,mmax);
            var hlen=houritem.length;
            var mlen=minitem.length;
            for(var a2=0;a2<hlen;a2++){
                for(var a3=0;a3<mlen;a3++){
                    var h=houritem[a2];
                    var m=minitem[a3];
                    if(h===0){
                        h="0";
                    }
                    if(m<10){
                        m="0"+m;
                    }
                    if(m===0){
                        m="00";
                    }
                    output.push(h+":"+m);
                }
            }
        }
        
        return output;
    };
    

Log in to reply
 

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