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

Solution:

The idea is simple, just generate all the possible answers and evaluate them using dfs.

The implementation is annoying, since you need to consider some corner cases.

Code:

public class Solution {
    
    String max = "" + Integer.MAX_VALUE;
    public List<String> addOperators(String num, int target) {
        List<String> ret = new ArrayList<String>();
        helper(ret,num,0,"",0,0,1,target);
        return ret;
    }
    
    /**
     * for example 1234 -> 
     * suppose we have  1 + 2 + 3 * 4 and we are at 1 + 2 + 3 4 and since we do not know whether we want have
     * 1 + 2 + 3 + 4 or 1 + 2 + 3 - 4 or 1 + 2 + 3 * 4, 
     * we need to record the value pre (1 + 2) = 3, and the value cur which is 3.
     * if we assign * after the 3, the pre remains (1 + 2) = 3, and the cur is 3 * 4 = 12.
     * if we assign + after the 3, the pre should be 1 + 2 + 3  = 6, and the cur is 4,
     * if we assign - after the 3, the pre should be 1 + 2 + 3 = 6, the sign should be -1, and cur is 4.
     * 
     * if(index == 0) we can only do "+"
     * if charAt(index) == '0' we can only have the value 0, since we do not allow number "04".
     * if the substring exceeds the value of Integer.MAX_VALUE we should break;
     * 
     */
    
    void helper(List<String> ret, String num, int index,String path, int pre, int cur, int sign,int target){
        int sum = pre + cur * sign;
        if(index == num.length()){
            if(target == sum)
                ret.add(path);
            return;
        }
        for(int i = index; i < num.length(); i++){
            if(num.charAt(index) == '0' && i > index) break;
            if(i - index == 9 && num.substring(index,i+1).compareTo(max) > 0) break;
            int v = Integer.parseInt(num.substring(index,i+1));
            if(index == 0){
                helper(ret,num,i + 1, "" + v, sum, v, 1,target);
            }
            if(index > 0){
                helper(ret,num,i + 1,path + "+" + v, sum, v, 1,target);
                helper(ret,num,i + 1,path + "-" + v, sum, v, -1,target);
                helper(ret,num,i + 1,path + "*" + v, pre, cur * v, sign,target);
            }
        }
    }
}



评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值