标签: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