forked from kamyu104/LeetCode-Solutions
-
Notifications
You must be signed in to change notification settings - Fork 1
/
verbal-arithmetic-puzzle.cpp
66 lines (62 loc) · 2.3 KB
/
verbal-arithmetic-puzzle.cpp
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
// Time: O(10!* n * l)
// Space: O(n * l)
class Solution {
public:
bool isSolvable(vector<string>& words, string result) {
for (auto& w : words) {
reverse(w.begin(), w.end());
}
reverse(result.begin(), result.end());
unordered_map<char, int> lookup;
unordered_set<int> used;
return backtracking(words, result, 0, 0, 0, &lookup, &used);
}
private:
bool backtracking(const vector<string>& words, const string& result,
int i, int j, int carry,
unordered_map<char, int> *lookup,
unordered_set<int> *used) {
if (j == result.length()) {
return carry == 0;
}
if (i != words.size()) {
if (j >= words[i].length() || lookup->count(words[i][j])) {
return backtracking(words, result, i + 1, j, carry, lookup, used);
}
for (int val = 0; val < 10; ++val) {
if (used->count(val) || (val == 0 && j == words[i].length() - 1)) {
continue;
}
(*lookup)[words[i][j]] = val;
used->emplace(val);
if (backtracking(words, result, i + 1, j, carry, lookup, used)) {
return true;
}
used->erase(val);
lookup->erase(words[i][j]);
}
return false;
}
const auto& total = accumulate(words.cbegin(), words.cend(), carry,
[&j, &lookup](const auto& x, const auto& y) {
return (j < y.length()) ? x + (*lookup)[y[j]] : x;
});
carry = total / 10;
int val = total % 10;
if (lookup->count(result[j])) {
return val == (*lookup)[result[j]] &&
backtracking(words, result, 0, j + 1, carry, lookup, used);
}
if (used->count(val) || (val == 0 && j == result.length() - 1)) {
return false;
}
(*lookup)[result[j]] = val;
used->emplace(val);
if (backtracking(words, result, 0, j + 1, carry, lookup, used)) {
return true;
}
used->erase(val);
lookup->erase(result[j]);
return false;
}
};