282. Expression Add Operators

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.

Examples:

"123", 6 -> ["1+2+3", "1*2*3"] 
"232", 8 -> ["2*3+2", "2+3*2"]
"105", 5 -> ["1*0+5","10-5"]
"00", 0 -> ["0+0", "0-0", "0*0"]
"3456237490", 9191 -> []

usually this case you need to traverse the string from the beginning, the recusively build the result for the left.

public class Solution {
    List<String> res = new ArrayList<>();
    public List<String> addOperators(String num, int target) {
        add(num, target, "", 0, 0);
        return res;
    }

    private void add(String num, int target, String tmp, long currRes, long prevNum){
        if(currRes == target && num.length()==0){
            String exp = new String(tmp);
            res.add(exp);
            return;
        }

        for(int i=1; i<= num.length();i++){
            String currStr = num.substring(0,i);
            if(currStr.length()>1 && currStr.charAt(0) == '0') return;
            String next = num.substring(i);
            long currNum = Long.parseLong(currStr);
            if(tmp.length() !=0){
                add(next, target, tmp+"+"+currNum, currRes+currNum, currNum);
                add(next, target, tmp+"-"+currNum, currRes-currNum, -currNum);
                add(next, target, tmp+"*"+currNum, (currRes-prevNum) + prevNum*currNum, prevNum*currNum);
            }else{
                add(next, target, currStr, currNum, currNum);
            }

        }

    }
}

results matching ""

    No results matching ""