题目
如题, 输入 n, 则从 1 打印至 99.
题解
考虑到 n 比较大会有大数问题, 所以使用字符数组存储数.
由题可用递归求 n 位全排列, 即为所得.
具体地, 用临时字符数组用来存答案, 每次递归填好一位, 都填好后输出.
代码
- import java.util.Scanner;
- public class Main {
- public static void main(String[] args) {
- Scanner s=new Scanner(System.in);
- int n=s.nextInt();
- printToN(n);
- }
- public static void printToN(int n) {
- char[] num=new char[n];
- composeNum(num,0,num.length);
- }
- //len 位全排列
- private static void composeNum(char[] num,int pos,int len) {
- if(pos==len) {// 此位不需要再填, 输出此时 num 即为所得
- printDelZero(num);
- }
- else {
- for(int i=0;i<10;++i) {
- num[pos]=(char) (i+'0');
- composeNum(num,pos+1,len);
- }
- }
- }
- // 删除前面的 0
- private static void printDelZero(char[] num) {
- int pos=0;
- for(;pos<num.length;++pos) {
- if(num[pos]!='0') {
- break;
- }
- }
- for(int i=pos;i<num.length;++i) {
- System.out.print(num[i]);
- }
- System.out.print("\n");
- }
- }
[剑指 Offer]17 - 打印从 1 到最大的 n 位数 (递归)
来源: http://www.bubuko.com/infodetail-3119773.html