【剑指offer】面试题 17. 打印从 1 到最大的 n 位数

面试题 17. 打印从 1 到最大的 n 位数
题目描述

题目:输入数字 n,按顺序打印出从 1 最大的 n 位十进制数。比如输入 3,则打印出 1、2、3 一直到最大的 3 位数即 999。

解答过程
样例
给出 n = 1, 返回[1,2,3,4,5,6,7,8,9].
给出 n = 2, 返回[1,2,3,4,5,6,7,8,9,10,11,...,99].

挑战
用递归完成,而非循环的方式。

Java 实现

public class Solution {
    /**
     * @param n: An integer
     * @return: An array storing 1 to the largest number with n digits.
     * 参考:https://blog.csdn.net/wutingyehe/article/details/51191520
     */
    public List<Integer> numbersByRecursion(int n) {
        // write your code here
        if(n<=0){
        	return new ArrayList<Integer>();
    	}else if(n==1){
    		List<Integer> result = new ArrayList<Integer>();
    		for(int i=1;i<=9;i++){
    			result.add(i);
    		}
    		return result;
    	}else{
    		List<Integer> list = numbersByRecursion(n-1);
    		List<Integer> result = new ArrayList<Integer>(list);
    		for(int i=1;i<=9;i++){
    			int topdigit = (int)Math.pow(10, n-1)*i;
    			result.add(topdigit);
    			for(int j=1;j<=list.size();j++){
    				result.add(topdigit+j);
    			}
    		}
    		return result;
    	}
    }
}
原文地址:https://www.cnblogs.com/hgnulb/p/9030240.html