You signed in with another tab or window. Reload to refresh your session.You signed out in another tab or window. Reload to refresh your session.You switched accounts on another tab or window. Reload to refresh your session.Dismiss alert
在递归函数中,首先判断当前解析到的变量的位置 cur 是否已经等于变量总个数了,是的话表示所有变量都解析完了,然后判断等式左边之和 sum 是否为0,是的话表示找到解了,返回 true,否则返回 false。若 cur 不等于变量总个数,则继续解析当前字母,还是尝试 [0, 9] 区间内的所有数字,当前已经用过的数字不能在用了,根据 used 数组来判断,还有若当前字母是某个单词的首字母,则不能为0,通过 nonLeadingZero 数组来判断。若当前值可用的话,则在 used 数组中标记为 true,然后调用递归函数,此时传入 cur+1,sum 变为 sum + charCnt[charList[cur]] * i,因为多解析了一个字母,所以要加上该解析值乘以其系数的值。若返回值为 true,则说明找着了,直接返回 true 即可。否则将该 used 中的该解析值充值为 false,for 循环退出后返回 false 即可,参见代码如下(注意这里所有的数组都没有用 C++ STL 中的 vector,而是用的C语言中的指针数组,不然会超时):
class Solution {
public:
bool isSolvable(vector<string>& words, string result) {
unordered_set<char> charSet;
int charCnt[91] = {};
bool nonLeadingZero[91] = {};
for (string word : words) {
int n = word.size();
for (int i = 0; i < n; ++i) {
if (i == 0 && n > 1) nonLeadingZero[word[i]] = true;
charSet.insert(word[i]);
charCnt[word[i]] += pow(10, n - 1 - i);
}
}
int n = result.size();
for (int i = 0; i < n; ++i) {
if (i == 0 && n > 1) nonLeadingZero[result[i]] = true;
charSet.insert(result[i]);
charCnt[result[i]] -= pow(10, n - 1 - i);
}
bool used[10] = {};
char charList[charSet.size()];
int i = 0;
for (char c : charSet) {
charList[i++] = c;
}
return dfs(charList, charCnt, 0, 0, nonLeadingZero, used, i);
}
bool dfs(char* charList, int* charCnt, int cur, int sum, bool* nonLeadingZero, bool* used, int numChars) {
if (cur == numChars) return sum == 0;
for (int i = 0; i <= 9; ++i) {
char c = charList[cur];
if (used[i] || (i == 0 && nonLeadingZero[charList[cur]])) continue;
used[i] = true;
if (dfs(charList, charCnt, cur + 1, sum + charCnt[charList[cur]] * i, nonLeadingZero, used, numChars)) return true;
used[i] = false;
}
return false;
}
};
Activity
[-][LeetCode] 1307. Missing Problem[/-][+][LeetCode] 1307. Verbal Arithmetic Puzzle[/+]