链接:. - 力扣(LeetCode)
题解:. - 力扣(LeetCode)
class Solution {
public:
int countSpecialNumbers(int n) {
if (n <= 0) {
return -1;
}
std::string str = to_string(n);
std::vector<std::vector<int>> memo(str.size(), std::vector<int>(1 << 10, -1));
bool is_limit = true;
int mask = 0;
bool is_num = false;
int begin = 0;
return dfs(str, begin, is_limit, is_num, mask, memo);
}
private:
int dfs(std::string& n, int begin, bool is_limit, bool is_num, int mask,
std::vector<std::vector<int>>& memo) {
if (begin == n.size()) {
if (is_num) {
return 1;
}
return 0;
}
if (!is_limit && is_num && memo[begin][mask] != -1) {
return memo[begin][mask];
}
int result = 0;
if (!is_num) {
result += dfs(n, begin+1, false, false, mask, memo);
}
int up = is_limit ? n[begin] - '0' : 9;
for (int i = 1 - is_num; i <= up; ++i) {
if ((1 << i) & mask) {
continue;
}
result += dfs(n, begin+1, is_limit && (i == up ? true : false),
true, mask | (1 << i), memo);
}
if (!is_limit && is_num) {
memo[begin][mask] = result;
}
return result;
}
};