LintCode 653: Expression Add Operators

  1. 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.

Example
Example 1:

Input:
“123”
6
Output:
[“123”,“1+2+3”]
Example 2:

Input:
“232”
8
Output:
[“23+2", "2+32”]
Example 3:

Input:
“105”
5
Output:
[“1*0+5”,“10-5”]
Example 4:

Input:
“00”
0
Output:
[“0+0”, “0-0”, “0*0”]
Example 5:

Input:
“3456237490”,
9191
Output:
[]

解法1:用DFS。
注意:
1)因为乘法优先级高,所以我们记下prevFactor,如果选择乘法,则将前面的prevFactor减去,再加上prevFactor与现在的number的乘积。
2) 用long long因为可能溢出。
3) 当输入为“00",同时target也为0时,输出可能是"00",应该将该可能性排除。



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) {
        int n = num.size();
        if (n == 0) return vector<string>();
        string sol;
        dfs(num, 0, sol, 0, 0, target);
        return sols;
    }

private:
    vector<string> sols;
    void dfs(string &num, int index, string sol, long long sum, long long prevFactor, int target) {
        int n = num.size();
        
        if (index == n && target == sum) {
            sols.push_back(sol);
            return;
        }
        
        for (int i = index; i < n; ++i) {
            string numStr = num.substr(index, i - index + 1);
            long long number = stoll(numStr);
            if (index == 0) {
                dfs(num, i + 1, numStr, number, number, target);
            } else {
                dfs(num, i + 1, sol + '+' + numStr, sum + number, number, target);
                dfs(num, i + 1, sol + '-' + numStr, sum - number, -number, target);
                dfs(num, i + 1, sol + '*' + numStr, sum - prevFactor + prevFactor * number, prevFactor * number, target);
            }
            
            if (num[index] == '0') break;  //to avoid "00"
        }
     
    }
};
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值