import java.util.Arrays;
/**
* 打印從1到最大的n位數 : https://leetcode-cn.com/problems/da-yin-cong-1dao-zui-da-de-nwei-shu-lcof/
* @Description
*/
public class Test15 {
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;
}
//考慮大數問題
private int[] res;
private int nine = 0, count = 0, start, n;
private char[] num, loop = {'0', '1', '2', '3', '4', '5', '6', '7', '8', '9'};
public int[] printNumbers2(int n) {
this.n = n;
res = new int[(int)Math.pow(10, n) - 1];
num = new char[n];
start = n - 1;
dfs(0);
return res;
}
private void dfs(int x) {
if(x == n) {
String s = String.valueOf(num).substring(start);
if(!s.equals("0")) res[count++] = Integer.parseInt(s);
if(n - start == nine) start--;
return;
}
for(char i : loop) {
if(i == '9') nine++;
num[x] = i;
dfs(x + 1);
}
nine--;
}
public static void main(String[] args) {
System.out.println(Arrays.toString(new Test15().printNumbers(6)));
}
}
劍指Offer-14-打印從1到最大的n位數
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.