首页 > 其他 > 详细

LeetCode 282: Expression Add Operation

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

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

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

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!