Assign binary operators to evaluate to target value

Given a string that contains only digits 0-9 and a target value, return all possibilities to add binary operators (not unary) +, -, or * between the digits so they evaluate to the target value.

For example:
“232”, 8 -> [“2*3+2”, “2+3*2”] “00”, 0 -> [“0+0+0”, “0-0”, “0*0”] “102”, 2 -> [“1*0+2”] “45435”, 9191 -> []

 

    public List<String> addOperators(String num, int target) {
        List<String> result = new ArrayList<String>();
        if(num == null || num.length() == 0) return result;
         
        addOperator(num, 0, "", target, 0, 0, result);
        return result;
    }
    
    private void addOperator(String num, int curPos, String curPath, int target, long curEval, long prevOpnd, List<String> res){
        if(curPos == num.length()){
            if(curEval == target){
                res.add(curPath);
            }
            return;
        }
        
        for(int i = curPos; i<num.length(); i++){
            if(i != curPos && num.charAt(curPos) == '0'){
                break;
            }
            
            long curOprnd = Long.parseLong(num.substring(curPos, i+1));
            if(curPos == 0){
                addOperator(num, i+1, curPath+curOprnd, target, curOprnd, curOprnd, res);
            }
            else{
                addOperator(num, i+1, curPath+"+"+curOprnd, target, curEval+curOprnd, curOprnd, res);
                addOperator(num, i+1, curPath+"-"+curOprnd, target, curEval-curOprnd, -curOprnd, res);
                addOperator(num, i+1, curPath+"*"+curOprnd, target, curEval-prevOpnd+prevOpnd*curOprnd, prevOpnd*curOprnd, res);
            }
        }
    }

Leave a Reply

Your email address will not be published. Required fields are marked *