栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 软件开发 > 后端开发 > Java

2021.10.11 - JZ17.打印从1到最大的n位数

Java 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

2021.10.11 - JZ17.打印从1到最大的n位数

文章目录
  • 1. 题目
  • 2. 思路
    • (1) DFS
  • 3. 代码

1. 题目

2. 思路 (1) DFS
  • 关键是利用深度优先搜索对每一个长度的数字进行全排列,如一位数字的全排列是1、2、……、9,两位数字的全排列是10、11、……、99,每一个长度的数字其全排列结果的第一位上的数字是1-9,其他位上的数字是0-9。
  • 首先单独对第一位赋值,然后递归对其他位赋值,每当对所有位赋完值后,将其加入结果集即可。
3. 代码
public class Test {
    public static void main(String[] args) {
    }
}

class Solution {
    private int[] res;
    private int count;

    public int[] printNumbers(int n) {
        res = new int[(int) Math.pow(10, n) - 1];
        count = 0;
        char[] num;
        for (int digit = 1; digit <= n; digit++) {
            for (char first = '1'; first <= '9'; first++) {
                num = new char[digit];
                num[0] = first;
                fullPermutation(num, 1, digit);
            }
        }
        return res;
    }

    private void fullPermutation(char[] num, int index, int digit) {
        if (index == digit) {
            res[count++] = Integer.parseInt(String.valueOf(num));
            return;
        }
        for (char i = '0'; i <= '9'; i++) {
            num[index] = i;
            fullPermutation(num, index + 1, digit);
        }
    }
}
转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/315074.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号