[LeetCode] 282. Expression Add Operators

Given a string that contains only digits 0-9 and a target value, return all possibilities to add binary operators (not unary) +-, or *between the digits so they evaluate to the target value.
Examples: 
"123", 6 -> ["1+2+3", "1*2*3"] 
"232", 8 -> ["2*3+2", "2+3*2"]
"105", 5 -> ["1*0+5","10-5"]
"00", 0 -> ["0+0", "0-0", "0*0"]
"3456237490", 9191 -> []

Thought process:
Divide and conquer. Backtracking. Iterate through all sub-string combinations. Add operators between numbers. Put path into result list if the calculated result equals target.
The characters may be combined to form a multi-digit number. So I need to iterate through all sub-string combinations. Note that the string "0d" cannot be simplified to d (0 can't be dropped). So skip the sub-strings that start with a 0.

Solution:

 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
class Solution {
    public List<String> addOperators(String num, int target) {
        List<String> list = new ArrayList<>();
        addOperators(num, target, 0, 0, "", list);
        return list;
    }
    
    private void addOperators(String num, long target, int start, long prevItem, String exp, List<String> list) {
        if (target == 0 && start == num.length()) {
            list.add(exp);
            return;
        }
        
        for (int i = start; i < num.length(); i++) {
            if (i > start && num.charAt(start) == '0') {
                return;
            }
            
            long n = Long.parseLong(num.substring(start, i + 1));
            if (start == 0) {
                addOperators(num, target - n, i + 1, n, exp + n, list);
            } else {
                addOperators(num, target - n, i + 1, n, exp + "+" + n, list);
                addOperators(num, target + n, i + 1, -n, exp + "-" + n, list);
                addOperators(num, target + prevItem - prevItem * n, i + 1, prevItem * n, exp + "*" + n, list);
            }
        }
    }
}

Time complexity:
For each character, there are four cases of the character that follows: +, -, *, and nothing. Say the length of the string is n. The overall time complexity is O(4^n).

Comments

Popular posts from this blog

[LeetCode] 714. Best Time to Buy and Sell Stock with Transaction Fee

[LeetCode] 269. Alien Dictionary

[LeetCode] 631. Design Excel Sum Formula