添加运算符-LintCode

这是一篇关于如何通过在数字字符串中添加二元运算符(加、减、乘)来得到特定目标值的博客。文章可能涉及算法和数学策略。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

给定一个仅包含数字 0 - 9 的字符串和一个目标值,返回在数字之间添加了 二元 运算符(不是一元)+, - 或 * 之后所有能得到目标值的情况。

样例:

"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 -> []
#ifndef C653_H
#define C653_H
#include<iostream>
#include<string>
#include<vector>
using namespace std;
class Solution {
public:
    /*
    * @param num: a string contains only digits 0-9
    * @param target: An integer
    * @return: return all possibilities
    */
    vector<string> addOperators(string &num, int target) {
        // write your code here
        vector<string> res;
        if (num.empty())
            return res;
        vector<string> dic{ "+", "-", "*" };
        string str;
        helper(num, str, target, 0, 0, 0, res);
        return res;
    }   
    /* str表示添加了运算符的字符串,pos表示当前位置,
     * curVal,preVal分别表示当前字符串运算的总和,上一步运算得到的值
     * n表示当前的数字,当运算符是加号,当前字符串运算的总和就是之前的总和加上当前数字,将本次得到的数字值置为上一步运算得到的值
     * 当运算符是乘号,需要减去上一步的值再加上上一步值与n的乘积
    */
    void helper(string num, string str, int target, int pos, long long curVal, long long preVal, vector<string> &res)
    {
        if (pos == num.size()&&curVal==target)
        {
            res.push_back(str);
            return;
        }
        for (int i = pos + 1; i <= num.size(); ++i)
        {
            string tmp = num.substr(pos,i-pos);
            long long n = stoll(tmp);
            if (tmp[0] == '0'&&tmp.size() > 1)
                break;
            if (pos == 0)
                helper(num, tmp, target, i, n, n, res);
            else
            {
                helper(num, str + "+" + tmp, target, i, curVal + n, n, res);
                helper(num, str + "-" + tmp, target, i, curVal - n, -n, res);
                helper(num, str + "*" + tmp, target, i, curVal - preVal + preVal*n, preVal*n, res);
            }
        }
    }
};
#endif
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值