Expression Add Operators

来源:互联网 发布:mysql函数 编辑:程序博客网 时间:2024/05/01 10:52
public class Solution {    public List<String> addOperators(String num, int target) {        List<String> res = new LinkedList<>();         helper(res, num, target, "", 0, 0);         return res;    }        private void helper(List<String> res, String num, int target, String temp, long curRes, long prevNum) {        if (curRes == target && num.length() == 0) {            res.add(new String(temp));            return;        }        for (int i = 1; i <= num.length(); i++) {            String curStr = num.substring(0, i);            if (curStr.length() > 1 && curStr.charAt(0) == '0') {                return;            }            long curNum = Long.valueOf(curStr);            String nextNum = num.substring(i);            if (temp.length() != 0) {                helper(res, nextNum, target, temp + '*' + curStr, curRes - prevNum + prevNum * curNum, prevNum * curNum);                helper(res, nextNum, target, temp + '+' + curStr, curRes + curNum, curNum);                helper(res, nextNum, target, temp + '-' + curStr, curRes - curNum, -curNum);            } else {                helper(res, nextNum, target, curStr, curNum, curNum);            }        }    }}

0 0
原创粉丝点击