My Simple Javascript AC solution


  • 0
    F

    My two steps javascript solution:

    1.find all subsets of num string
    2.backtracking all the operator commination for each subset

    Issue:

    Try to evaluate using eval not quite working

    var re=function(arr,len,res,num,target,temp,m){
        	if(arr===len){
        		if(target ===0)
        			res.push(temp.join('').substring('1'));
                return;
            }
            var t=/^0[0-9]+/;
            if(t.test(num[arr])){
            	return;
            }
        	temp.push('+'+num[arr]);
        	re(arr+1,len,res,num,target-parseInt(num[arr]),temp,parseInt(num[arr]));
        	temp.pop();
        	if(arr){
        	temp.push('-'+num[arr]);
        	re(arr+1,len,res,num,target+parseInt(num[arr]),temp,parseInt('-'+num[arr]));
        	temp.pop();
        	temp.push('*'+num[arr]);
        	re(arr+1,len,res,num,target+m-m*parseInt(num[arr]),temp,parseInt(m)*parseInt(num[arr]));
        	temp.pop();
        	}
        }
    //get subset
        var conb=function(num,s,target,res){
        	var t,t1,temp=[],len=num.length;
        	for(var i=s+1;i<=len-1;i++){
        		t=num.substring(0,i)+'&'+num.substring(i);
        		t1=t.split('&');
        		re(0,t1.length,res,t1,target,temp,0);
        		conb(t,i+1,target,res);
        	}
        }
        var addOperators = function(num, target) {
            if(!num.length){
                return [];
            }
            if(num.length===Math.abs(target).toString().length){
            	return target==num ? [num]:[];
            }
            var res=[]; 
            conb(num,0,target,res);
            return res;
        };

Log in to reply
 

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