2017-09-13 LeetCode_282 Expression Add Operators

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

Credits:
Special thanks to @davidtan1890 for adding this problem and creating all test cases.

solution:

#include <stack>
2
class Solution {
3
public:
4
    void divides(vector<string>& ans, string& num, int target, string str, int d, bool flag, stack<long long> nums, stack<char> syms, int state) {
5
        if (state == 0) {
6
            nums.top() = nums.top()*10+num[d-1]-'0';
7
        } else if (state == 1 || state == 2) {
8
            while (syms.size()) {
9
                long long x = nums.top(); nums.pop();
10
                if (syms.top() == '+') nums.top() += x;
11
                else if (syms.top() == '-') nums.top() -= x;
12
                else nums.top() *= x;
13
                syms.pop();
14
            }
15
            if (state == 1) syms.push('+');
16
            else syms.push('-');
17
            nums.push(num[d-1]-'0');
18
        } else {
19
            while (syms.size() && syms.top() == '*') {
20
                long long x = nums.top(); nums.pop();
21
                nums.top() *= x; syms.pop();
22
            }
23
            syms.push('*');
24
            nums.push(num[d-1]-'0');
25
        }
26
        if (d == num.length()) {
27
            while (syms.size()) {
28
                long long x = nums.top(); nums.pop();
29
                if (syms.top() == '+') nums.top() += x;
30
                else if (syms.top() == '-') nums.top() -= x;
31
                else nums.top() *= x;
32
                syms.pop();
33
            }
34
            if (target == nums.top()) ans.push_back(str);
35
            return;
36
        }
37
        if (flag) divides(ans, num, target, str+num[d], d+1, true, nums, syms, 0);
38
        divides(ans, num, target, str+"+"+num[d], d+1, num[d]-'0', nums, syms, 1);
39
        divides(ans, num, target, str+"-"+num[d], d+1, num[d]-'0', nums, syms, 2);
40
        divides(ans, num, target, str+"*"+num[d], d+1, num[d]-'0', nums, syms, 3);
41
    }
42
    vector<string> addOperators(string num, int target) {
43
        vector<string> ans;
44
        if (num.length() == 0) return ans;
45
        string str; str += num[0];
46
        stack<long long> nums; nums.push(0);
47
        stack<char> syms;
48
        divides(ans, num, target, str, 1, num[0]-'0', nums, syms, 0);
49
        return ans;
50
    }
51
};






评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值