码迷,mamicode.com
首页 > 其他好文 > 详细

LeetCode 282: Expression Add Operation

时间:2017-09-04 15:04:56      阅读:164      评论:0      收藏:0      [点我收藏+]

标签:with   targe   expr   exp   add   long   rto   blog   layer   

Note:

1. When real index is 0. It will be only add as first element without any opeartors.

2. When the starting char of one layer is ‘0‘, it should break since it could not be 01, 02, 03......

class Solution {
    public List<String> addOperators(String num, int target) {
        List<String> result = new ArrayList<>();
        generateOperators(result, num, "", 0, 0, target, 0L);
        return result;
    }
    
    private void generateOperators(List<String> result, String num, String current, int index, long value, int target, long multi) {
        if (index == num.length()) {
            if (value == target) {
                result.add(current);
            }
            return;
        }
        
        for (int i = index; i < num.length(); i++) {
            if (i != index && num.charAt(index) == ‘0‘) {
                break;
            }
            
            long data = Long.parseLong(num.substring(index, i + 1));
            
            if (index == 0) {
                generateOperators(result, num, current + num.substring(index, i + 1), i + 1, value + data, target, data);
            } else {
                generateOperators(result, num, current + "+" + num.substring(index, i + 1), i + 1, value + data, target, data);
                generateOperators(result, num, current + "-" + num.substring(index, i + 1), i + 1, value - data, target, -data);
                generateOperators(result, num, current + "*" + num.substring(index, i + 1), i + 1, value - multi + multi * data, target, multi * data);
            }
        }
    }
}

 

LeetCode 282: Expression Add Operation

标签:with   targe   expr   exp   add   long   rto   blog   layer   

原文地址:http://www.cnblogs.com/shuashuashua/p/7473246.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!