2048.下一个更大的数值平衡数
链接:2048.下一个更大的数值平衡数
难度:Medium
标签:数学、回溯、枚举
简介:给你一个整数 n ,请你返回 严格大于 n 的 最小数值平衡数 。
题解 1 - python
- 编辑时间:2023-12-09
- 执行用时:3380ms
- 内存消耗:15.98MB
- 编程语言:python
- 解法介绍:枚举。
class Solution:
    def nextBeautifulNumber(self, n: int) -> int:
        while True:
            n = n + 1
            arr = [0] * 10
            for c in str(n):
                arr[int(c)] += 1
            f = True
            for i in range(10):
                if arr[i] != 0 and arr[i] != i:
                    f = False
                    break
            if f:
                return n
题解 2 - cpp
- 编辑时间:2022-05-06
- 执行用时:4ms
- 内存消耗:7.03MB
- 编程语言:cpp
- 解法介绍:打表。
class Solution {
    public:
        void getNumber(int d, int ind, vector<int>& buff, vector<int>& arr) {
            if (d == 0) {
                vector<int> temp;
                for (auto x : buff) {
                    for (int i = 0; i < x; i++) {
                        temp.push_back(x);
                    }
                }
                do {
                    int num = 0;
                    for (auto x : temp) num = num * 10 + x;
                    arr.push_back(num);
                } while (next_permutation(temp.begin(), temp.end()));
                return;
            }
            for (int i = ind; i <= d; i++) {
                if (d - i > i || i == d) {
                    buff.push_back(i);
                    getNumber(d - i, i + 1, buff, arr);
                    buff.pop_back();
                }
            }
        }
        void getAllNumber(int d, vector<int>& arr) {
            vector<int> buff;
            getNumber(d, 1, buff, arr);
        }
        int nextBeautifulNumber(int n) {
            if (n == 0) return 1;
            int d = floor(log10(n)) + 1;
            vector<int> arr;
            getAllNumber(d, arr);
            getAllNumber(d + 1, arr);
            int ans = INT_MAX;
            for (auto x : arr) {
                if (x > n) ans = min(ans, x);
            }
            return ans;
        }
};