738. Monotone Increasing Digits(贪心)

1.题目描述

Given a non-negative integer N, find the largest number that is less than or equal to N with monotone increasing digits.

(Recall that an integer has monotone increasing digits if and only if each pair of adjacent digits x and y satisfy x <= y.)

Example 1:
Input: N = 10
Output: 9
Example 2:
Input: N = 1234
Output: 1234
Example 3:
Input: N = 332
Output: 299

Note: N is an integer in the range [0, 10^9].

2.代码

思路:遇到第一个元素 copy[i]<copy[i1] 时,从 copy[i1] 开始重写(减少最小),如 12387990 重写为 12379999 。rewriteCopy方法是从首位开始重写,实际与recover方法重写是一样的,有点冗余了。
方法:简单的自顶向下分解。

class Solution {
public:
    int monotoneIncreasingDigits(int N) {
        int t = N;
        vector<int> digits;
        for(int t = N, r = t%10; t != 0; r = t%10) {
            digits.push_back(r);
            t /= 10;
        }

        vector<int> copy(digits.begin(),digits.end());
        reverse(copy.begin(),copy.end());
        for(int i = 1; i < copy.size(); ++i) {
            if(copy[i] < copy[i-1]) {
                checkPre(copy, i);      
            }

        }
        int res = 0;
        for(int i = 0; i < copy.size(); ++i) {
            res = (res*10 + copy[i]);
        }
        return res;
    }
    void checkPre(vector<int>& copy, int index) {
        if(index-1 == 0) {
            rewriteCopy(copy);
            return;
        } else {
            recover(copy, index-1);                 
        }
    }
    void rewriteCopy(vector<int>& copy) {
        vector<int> res;
        if(copy[0] == 1) {
            res.push_back(9);
            for(int i = 0; i < copy.size()-2;++i) {
                res.push_back(9);
            } 
        } else {
            res.push_back(copy[0]-1);
            for(int i = 0; i < copy.size()-1;++i) {
                res.push_back(9);
            }           
        }
        copy = res;
    }
    void recover(vector<int>&copy, int index) {
        copy[index] -= 1;
        for(int i = index+1; i < copy.size(); ++i) {
            copy[i] = 9;
        }
        //递归从index-1开始重写 
        if(index-1>=0)  {
            if(copy[index] < copy[index-1]) {
                recover(copy, index-1);     
            }           
        }
        return;
    }
    void print(vector<int>& out) {
        for(int i = 0; i < out.size(); ++i)
            cout<< out[i] << " ";
        cout << endl;
    }
};

联系邮箱:sysuygm@163.com
欢迎指教。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值