package com.heu.wsq.leetcode.inoffer;
import java.util.ArrayList;
import java.util.List;
/**
* 剑指 Offer 17. 打印从1到最大的n位数
* @author wsq
* @date 2020/12/7
* 输入数字 n,按顺序打印出从 1 到最大的 n 位十进制数。比如输入 3,则打印出 1、2、3 一直到最大的 3 位数 999。
*
* 示例 1:
*
* 输入: n = 1
* 输出: [1,2,3,4,5,6,7,8,9]
*
* 链接:https://leetcode-cn.com/problems/da-yin-cong-1dao-zui-da-de-nwei-shu-lcof
*/
public class Offer17 {
/**
* 力扣上的版本,不考虑大数的情况
* @param n
* @return
*/
public int[] printNumbers(int n) {
int[] ans = new int[(int) Math.pow(10, n) - 1];
for (int i = 0; i < ans.length; i++) {
ans[i] = i + 1;
}
return ans;
}
/**
* 将这道题当成大数去做,也就是说n表示的位数可能远远不能用数字类型表示
* 1. 使用字符数组模拟字符串相加的过程
* 2. 由于是n位数,每一位都是从0到9,因此可以使用回溯的思想去解决,也就是全排列
* @param n
* @return
*/
public List<String> printNumbers2(int n){
if(n < 0){
return new ArrayList<>();
}
// char占用两个字节
char[] path = new char[n];
List<String> ans = new ArrayList<>();
// 第一位从0开始
for(int i = 0; i < 10; i++){
path[0] = (char) (i + '0');
dfs(1, path, ans, n);
}
return ans;
}
public void dfs(int index, char[] path, List<String> ans, int len){
if(index >= len){
int pos = 0;
while(pos < len && path[pos] == '0'){
pos++;
}
if (pos == len)
ans.add("0");
else {
ans.add(new String(path, pos, len - pos));
}
return;
}
for (int i = 0; i < 10; i++){
path[index] = (char)(i + '0');
dfs(index + 1, path, ans, len);
}
}
public static void main(String[] args) {
int n = 2;
Offer17 offer17 = new Offer17();
List<String> list = offer17.printNumbers2(n);
for (String s : list) {
System.out.println(s);
}
}
}
剑指 Offer 17. 打印从1到最大的n位数(大数情况,数字类型表示不下时)
最新推荐文章于 2025-11-24 14:46:26 发布
该博客介绍了如何实现从1到最大n位数的打印,包括两种方法:一种是直接生成数组,适用于较小的n;另一种是使用回溯算法模拟大数的生成,适用于任意大的n位数。博主通过递归的深度优先搜索(DFS)遍历所有可能的n位数组合,生成并返回结果列表。
159

被折叠的 条评论
为什么被折叠?



