其他分享
首页 > 其他分享> > Leetcode 282. Expression Add Operators

Leetcode 282. Expression Add Operators

作者:互联网

家里网络坏了,暂时无法上传图片

方法1: 这道题我尝试了好几个小时,做到后面越来越晕,都不知道自己在干嘛了。后来看了discussion的高票回答,觉得写得特别好,这边我给出链接。复杂度分析复盘的时候再看吧。

public class Solution {
    public List<String> addOperators(String num, int target) {
        List<String> rst = new ArrayList<String>();
        if(num == null || num.length() == 0) return rst;
        helper(rst, "", num, target, 0, 0, 0);
        return rst;
    }
    public void helper(List<String> rst, String path, String num, int target, int pos, long eval, long multed){
        if(pos == num.length()){
            if(target == eval)
                rst.add(path);
            return;
        }
        for(int i = pos; i < num.length(); i++){
            if(i != pos && num.charAt(pos) == '0') break;
            long cur = Long.parseLong(num.substring(pos, i + 1));
            if(pos == 0){
                helper(rst, path + cur, num, target, i + 1, eval + cur, cur);
            }
            else{
                helper(rst, path + "+" + cur, num, target, i + 1, eval + cur , cur);
                
                helper(rst, path + "-" + cur, num, target, i + 1, eval -cur, -cur);
                
                helper(rst, path + "*" + cur, num, target, i + 1, eval - multed + multed * cur, multed * cur );
            }
        }
    }
}

总结:

标签:cur,helper,Operators,pos,Add,num,rst,282,target
来源: https://blog.csdn.net/GoodJobJasper/article/details/113071365