7.22 第一次做,无法 AC,考虑大数的情况有点难想!看面试好像也出的不多!先跳过!
题目描述
原题链接:https://leetcode-cn.com/problems/da-yin-cong-1dao-zui-da-de-nwei-shu-lcof/
解题思路一:不考虑大数(面试可能不出,肯定得考虑大数)
K 神题解:https://leetcode-cn.com/problems/da-yin-cong-1dao-zui-da-de-nwei-shu-lcof/solution/
class Solution {public int[] printNumbers(int n) {int end = (int)Math.pow(10, n) - 1; // 关键int[] res = new int[end];for(int i = 0; i < end; i++) {res[i] = i + 1;}return res;}}
解题思路二:考虑大数(有点难!先跳过!)
卧槽,有点难!先跳过!
考虑大数时,返回值得为 String,int 类型会越界!
K 神有个写错了:

class Solution {StringBuilder res;int nine = 0, start, n; // nine: 遍历了多少次9的个数,start: 取值的左边界,保证将左边的0忽略掉,n: 位数char[] num, loop = {'0', '1', '2', '3', '4', '5', '6', '7', '8', '9'};public String printNumbers(int n) {this.n = n;res = new StringBuilder();num = new char[n];start = n - 1;dfs(0);res.deleteCharAt(res.length() - 1);return res.toString();}void dfs(int x) {if(x == n) {String s = String.valueOf(num).substring(start); // substring 也可以传一个参数,表示从此开始if(!s.equals("0")) res.append(s + ",");if(n - start == nine) start--; // 009、099的时候会执行return;}for(char i : loop) {if(i == '9') nine++;num[x] = i;dfs(x + 1);}nine--; // 进位了,所以 9 消失了}}
