1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109
| class Solution { private String maxValue = String.valueOf(Integer.MAX_VALUE);
public List<String> addOperators(String num, int target) { List<String> result = new ArrayList<>(); List<Integer> nums = new ArrayList<>(); for (int i = 0; i < num.length(); i++) { String left = num.substring(0, i + 1); if (!isValid(left)) { break; } Integer leftNum = Integer.parseInt(left, 10); nums.add(leftNum); search(result, num, i + 1, nums, new ArrayList<>(), target); nums.remove(nums.size() - 1); } return result; }
private void search(List<String> result, String num, int start, List<Integer> nums, List<Character> ops, int target) { if (start == num.length()) { if (isEqual(nums, ops, target)) { String item = convert(nums, ops); result.add(item); }
return; }
for (int i = start; i < num.length(); i++) { String left = num.substring(start, i + 1); if (!isValid(left)) { break; } Integer leftNum = Integer.parseInt(left, 10); nums.add(leftNum); ops.add('+'); search(result, num, i + 1, nums, ops, target); ops.set(ops.size() - 1, '-'); search(result, num, i + 1, nums, ops, target); ops.set(ops.size() - 1, '*'); search(result, num, i + 1, nums, ops, target);
nums.remove(nums.size() - 1); ops.remove(ops.size() - 1); } }
private String convert(List<Integer> nums, List<Character> ops) { StringBuilder sb = new StringBuilder(); sb.append(nums.get(0)); for (int i = 0; i < ops.size(); i++) { sb.append(ops.get(i)).append(nums.get(i + 1)); } return sb.toString(); }
private boolean isEqual(List<Integer> nums, List<Character> ops, int target) { Deque<Integer> numQueue = new LinkedList<>(); Deque<Character> opQueue = new LinkedList<>(); numQueue.addLast(nums.get(0)); int i = 1; int j = 0; while (i < nums.size()) { numQueue.addLast(nums.get(i)); if (ops.get(j) == '*') { int first = numQueue.pollLast(); int second = numQueue.pollLast(); if (first != 0 && Integer.MAX_VALUE / first < second) { return false; } int temp = first * second; numQueue.addLast(temp); } else { opQueue.addLast(ops.get(j)); } i++; j++; }
while (!opQueue.isEmpty()) { int first = numQueue.pollFirst(); int second = numQueue.pollFirst(); int temp; if (opQueue.pollFirst() == '+') { temp = first + second; } else { temp = first - second; }
numQueue.addFirst(temp); }
return numQueue.pollFirst() == target; }
private boolean isValid(String num) { if (num.length() == 1) { return true; }
if (num.charAt(0) == '0') { return false; }
return num.length() < maxValue.length() || num.compareTo(maxValue) < 1; } }
|