给定两个字符串 low 和 high 表示两个整数 low 和 high ,其中 low <= high ,返回 范围 [low, high] 内的 「中心对称数」总数 。
中心对称数 是一个数字在旋转了 180 度之后看起来依旧相同的数字(或者上下颠倒地看)。
示例 1:
输入: low = “50”, high = “100”
输出: 3
示例 2:
输入: low = “0”, high = “0”
输出: 1
提示:
1 <= low.length, high.length <= 15
low 和 high 只包含数字
low <= high
low and high 不包含任何前导零,除了零本身。
来源:力扣(LeetCode)
链接:https://leetcode.cn/problems/strobogrammatic-number-iii
方法一:DFS
C++提交内容:
class Solution {
public:
int strobogrammaticInRange(string low, string high) {
int ans=0;
string s[]={"","0","1","8"},l[]={"0","1","6","8","9"},r[]={"0","1","9","8","6"};
function<void(string)>dfs=[&](string str){
if(low.size()<=str.size() && str.size()<=high.size()){
if(str.size()==high.size() && str>high) return;
if((str.size()==low.size() && str>=low) || str.size()>low.size()){
if(str.size()==1 || str[0]!='0')ans++;
}
}
if(str.size()+2<=high.size()){
for(int i=0;i<5;i++)
dfs(l[i]+str+r[i]);
}
};
for(auto&str:s)dfs(str);
return ans;
}
};