leetcode788

旋转数字

思路:只有题目中出现2 5 6 9才可能是好数,如果出现了3 4 7,那么直接返回false。

数据范围是[1, 10000],所以暴力枚举可以过。

class Solution {
public:
    
    bool ok(int num){
        //统计数字中是否出现2 5 6 9,如果可以,那么才可能是好数
        int cnt = 0;
        while(num){
            int x = num % 10;
            num /=10;
            if(x == 2 || x == 5 || x == 6 || x == 9)
                cnt++;
            else if(x == 0 || x == 1 || x == 8)
                continue;
            else
                return false;
        }
        return cnt > 0;
    }
    int rotatedDigits(int n) {
        int res = 0;
        for(int i = 1; i <= n; i++){
            if(ok(i))
                res++;
        }
        return res;
    }
};

做完看了一下别人的题解发现可以用数位dp做。思路就是将数字转化为字符串,然后声明一个dp数组来记忆化搜索过的状态。

设置一个dif数组对10个数字进行分类。

class Solution {
public:
    vector<vector<int>> dp;
    string str;
    int len;
    int dif[10] = {0, 0, 1, -1, -1, 1, 1, -1, 0, 1};
    /* 
    @is_limit当前位置是否受到前一位的限制
    @has_diffs是否含有2 5 6 9其中的一位
     */
    int dps(int index, bool is_limit, int has_diffs){
        if(index == len) return has_diffs;
        //只有无限制的才是搜索完的,才可以返回
        if(!is_limit && dp[index][has_diffs] >= 0) return dp[index][has_diffs];
        int res = 0;
        int up = is_limit ? str[index] - '0' : 9;
        for(int i = 0; i <= up; i++)
            if(dif[i] != -1) //该位置不是 3 4 7
                res += dps(index+1, is_limit && i == up, has_diffs || dif[i]);  
        if(!is_limit) dp[index][has_diffs] = res;
        return res;
    }
    int rotatedDigits(int n) {
        str = to_string(n);
        len = str.size();
        dp.resize(len, vector<int>(2,-1));
        return dps(0, true, 0);
    }
};


 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值