《leetcode》:Expression Add Operators

来源:互联网 发布:大屏数据 编辑:程序博客网 时间:2024/05/29 10:49

题目

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 -> []

思路

此题比较难,不太好想,自己在看到这个题目的时候也感觉算法思想应该是这么来做,但是就是不太清晰,不知道应该怎么来写代码来实现。

参考于这里:https://discuss.leetcode.com/topic/24523/java-standard-backtrace-ac-solutoin-short-and-clear/2

实现代码如下:

    public class Solution {        private String num;        private int target;        public List<String> addOperators(String num, int target) {           List<String> res = new ArrayList<String>();           int len = num.length();           if(len==0){               return res;           }           this.num = num;           this.target = target;           addOperatorsHelper(res,"",0,0,0);           return res;        }        private void addOperatorsHelper(List<String> res, String path,                 int pos, long eval, long mult) {            if(pos==this.num.length()){                if(eval==this.target){                    res.add(path);                }                return;            }            for(int i=pos;i<this.num.length();i++){                if(i!=pos&&this.num.charAt(pos)=='0'){//多位数的第一位数不能为0                    break;                }                Long cur = Long.parseLong(this.num.substring(pos, i+1));                if(pos==0){                    addOperatorsHelper(res,path+cur,i+1,cur,cur);                }                else{                    addOperatorsHelper(res,path+"+"+cur,i+1,eval+cur,cur);                    addOperatorsHelper(res,path+"-"+cur,i+1,eval-cur,-cur);//注意这里是负cur                    addOperatorsHelper(res,path+"*"+cur,i+1,eval-mult+cur*mult,cur*mult);                }            }        }    }
0 0
原创粉丝点击