当前位置

网站首页> 程序设计 > 开源项目 > 程序开发 > 浏览文章

[LeetCode]Expression Add Operators - EpoTalk

作者:小梦 来源: 网络 时间: 2024-02-05 阅读:

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

分析

这道题首先想到的DFS, 递归结束时检查总值是否等于target,是的话把当前结果加入list里。

关键点是对于乘法,怎么处理当前总和的问题,这里用的方法是存一个prevVal,用来表示上一步的数,遇到乘号,就先在当前总和基础上减去上一步的值,然后再加上上一步的值与当前数的乘积。

另外有些小地方要注意,比如遇到‘0’这样的我们只考虑单独的数字0,不考虑其他以‘0’开头的字符串。

复杂度

time: O(4^n), space: O(n)

代码

public class Solution {    public List<String> addOperators(String num, int target) {        List<String> res = new ArrayList<String>();        dfs(res, num, target, 0, 0, 0, "");        return res;    }        public void dfs(List<String> res, String num, int target, int start, long currVal, long prevVal, String currExpr) {        if (start == num.length()) {if (currVal == target) {    res.add(currExpr);}return;        }    for (int i = start + 1; i <= num.length(); i++) {String expr = num.substring(start, i);long val = Long.parseLong(expr);// 对于'0'开头的非单独'0'字符串,直接跳出if (num.charAt(start) == '0' && i != start + 1) {    break;}// 最开始的当前表达式只是加个数字if (start == 0) {    dfs(res, num, target, i, val, val, expr);} else {    dfs(res, num, target, i, currVal + val, val, currExpr + "+" + expr);    dfs(res, num, target, i, currVal - val, -val, currExpr + "-" + expr);    dfs(res, num, target, i, currVal - prevVal + prevVal * val, prevVal * val, currExpr + "*" + expr);}        }    }}

热点阅读

网友最爱