leetcode282 : Expression Add Operators

1、原题如下:
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 -> []

2、解题如下:

class Solution {
public:
    void dfs(vector<string>& result, const string num, const int target, int pos, string os, const long calres, const char lo, const long ln)
    {
        if (pos == num.size() && calres == target)
            result.push_back(os);
        else
        {
            for (int i = pos + 1; i <= num.size(); i++)
            {
                string nos = num.substr(pos, i - pos);
                long nol = stol(nos);
                if (to_string(nol).size() != i - pos) continue;
                dfs(result, num, target, i, os + '+' + nos, calres + nol, '+', nol);
                dfs(result, num, target, i, os + '-' + nos, calres - nol, '-', nol);
                dfs(result, num, target, i, os + '*' + nos, (lo == '+') ? (calres - ln + ln*nol) : (lo == '-') ? (calres + ln - ln*nol) : ln*nol, lo, ln*nol);
            }
        }
    }
    //fos:first operational string
    //fol:first operational long
    //nos:next  operational string
    //nol:next  operational long
    //lo:last operator
    //ln:last number
    vector<string> addOperators(string num, int target) {
        vector<string> result;
        if (!num.size())  return result;
        for (int i = 1; i <= num.size(); i++)
        {
            string fos = num.substr(0, i);//切割出第一个操作数
            long fol = stol(fos);
            if (to_string(fol).size() != i) continue;
            dfs(result, num, target, i, fos, fol, ' ', fol);//(point1)

        }
        return result;
    }
};

3、总结
这道题主要用的是dfs深度检索,遍历所有可能出现的情况。其实我们设想,如果num.size()为9,那就相当于有八个地方可以添加符号,我们可以选择填或者不填,虽然每两个数之间只能填一个操作符,但是总共填多少个并不限制,如此就会有很多种情况。point1之前首先确定第一个操作数,至于它到底有几位,我们根据循环来逐次遍历。然后启动dfs遍历功能,然后循环迭代,考虑下一个添加符号的位置在哪里(还是逐次遍历)操作完所有数之后就进行判断,看是否计算结果符合,符合就插入,不符合就继续之前的dfs~

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值