Java Solution


  • 0
    V
    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);
                }
    
            }
    
        }
    }
    

Log in to reply
 

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