LeetCode 题解(211) : 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 -> []
题解:

注意的问题:

1. 有可能string很长,所以要用长整数。

2.需要记录last oprand,为的是处理乘号的情况。乘号时的计算公式为: result - lastOP + lastOP * curVaule,如 2 + 3 * 5, 当计算到要乘5时,result = 2 + 3 = 5, lastOp = 3, curValue = 5, 则最终结果为: 5 - 3 + 3 * 5 = 17 = 2 + 3 * 5。

3. 记录当前结果,用于在num长度为零时, 判断是否与target相等,并加入最终的results中。

4. 需要跳过长于一个零的操作数,如“00”, “000”, etc.

5. 按左操作数从长度为1 到长度为len(num)循环, 并递归。

C++版:

class Solution {
public:
    vector<string> addOperators(string num, int target) {
        vector<string> results;
        opRecur(num, target, 0, 0, "", results);
        return results;
    }
    
    void opRecur(string num, int target, long long lastOp, long long result, string expression, vector<string> & results) {
        if(num.length() == 0 && result == target) {
            results.push_back(expression);
            return;
        }
        for(int i = 1; i <= num.length(); i++) {
            string cur = num.substr(0, i);
            string rest = num.substr(i);
            long long curV = stoll(cur);
            if(cur.length() > 1 && cur[0] == '0')
                continue;
            if(expression.length() == 0) {
                opRecur(rest, target, curV, curV, cur, results);
            } else {
                opRecur(rest, target, curV, result + curV, expression + "+" + cur, results);
                opRecur(rest, target, -curV, result - curV, expression + "-" + cur, results);
                opRecur(rest, target, lastOp * curV, result - lastOp + lastOp * curV, expression + "*" + cur, results);
            }
        }
    }
};

Java版:

public class Solution {
    public List<String> addOperators(String num, int target) {
        List<String> results = new ArrayList<>();
        opRecur(num, target, 0, 0, "", results);
        return results;
    }
    
    private void opRecur(String num, int target, long lastOp, long result, String expression, List<String> results) {
        if(num.length() == 0) {
            if(target == result)
                results.add(expression);
            return;
        } 
        for(int i = 1; i <= num.length(); i++) {
            String cur = num.substring(0, i);
            if(cur.length() > 1 && cur.charAt(0) == '0')
                continue;
            String rest = num.substring(i);
            long curV = Long.parseLong(cur);
            if(expression.length() == 0) {
                opRecur(rest, target, curV, curV, expression + cur, results);
            } else {
                opRecur(rest, target, curV, result + curV, expression + "+" + cur, results);
                opRecur(rest, target, -curV, result - curV, expression + "-" + cur, results);
                opRecur(rest, target, curV * lastOp, result - lastOp + lastOp * curV, expression + "*" + cur, results);
            }
        }
    }
}

Python版:

class Solution(object):
    def addOperators(self, num, target):
        """
        :type num: str
        :type target: int
        :rtype: List[str]
        """
        results = []
        self.opRecur(num, target, 0, 0, "", results)
        return results
        
    def opRecur(self, num, target, lastOp, result, expression, results):
        if len(num) == 0:
            if target == result:
                results.append(expression)
            return
        
        for i in range(1, len(num) + 1):
            cur = num[:i]
            if len(cur) > 1 and cur[0] == "0":
                continue
            rest = num[i:]
            curV = int(cur)
            if len(expression) == 0:
                self.opRecur(rest, target, curV, curV, expression + cur, results)
            else:
                self.opRecur(rest, target, curV, result + curV, expression + "+" + cur, results)
                self.opRecur(rest, target, -curV, result - curV, expression + "-" + cur, results)
                self.opRecur(rest, target, lastOp * curV, result - lastOp + lastOp * curV, expression + "*" + cur, results)

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值