[leetcode] 248. Strobogrammatic Number III 解题报告

本文介绍了LeetCode第248题的解题报告,该题要求计算在指定范围内旋转对称数(上下翻转不变的数字)的数量。例如,在50到100之间,有3个旋转对称数:69、88和96。解题策略是枚举不同长度的旋转对称数,并在末尾检查它们是否在给定范围内,注意避免整型溢出问题。

题目链接: https://leetcode.com/problems/strobogrammatic-number-iii/

A strobogrammatic number is a number that looks the same when rotated 180 degrees (looked at upside down).

Write a function to count the total strobogrammatic numbers that exist in the range of low <= num <= high.

For example,
Given low = "50", high = "100", return 3. Because 69, 88, and 96 are three strobogrammatic numbers.

Note:
Because the range might be a large number, the low and high numbers are represented as string.


思路: 和之前的II一样, 在上一题中让求固定长度的答案, 而这题给了一个范围, 这个范围可能包含了几个长度, 所以只要枚举一样不同长度的答案并且在最后的时候判断一下是否在给定的范围内即可. 需要注意的是可能会整型溢出, 所以在判断答案范围的时候要用long类型.

代码如下:

class Solution {
public:
    void DFS(string& low, string& high, int n, string str)
    {
        if(n==0 && stol(str)>=stol(low) && stol(str)<=stol(high)) {Max++; return;}
        if(n%2==1) for(auto val: same) DFS(low, high, n-1, val);
        if(n==0 || n%2==1) return;
        for(int i = (n==2?1:0); i< two.size(); i++)
            DFS(low, high, n-2, two[i].first+str+two[i].second);
    }
    
    int strobogrammaticInRange(string low, string high) {
        int n1 = low.size(), n2 = high.size();
        for(int i = n1; i <= n2; i++) DFS(low, high, i, "");
        return Max;
    }
private:
    int Max = 0;
    vector<string> same{"0", "1", "8"};
    vector<pair<char,char>> two{{'0','0'},{'1','1'},{'6','9'},{'8','8'},{'9','6'}};
};


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值