劍指 Offer 17 列印從1到最大的n位數
阿新 • • 發佈:2021-01-11
技術標籤:leetcode劍指offer面試演算法java資料結構leetcode
題目:輸入一個位數n,把1到最大的n位數(如當n=2時,為99)放到int[]裡返回。
public int[] printNumbers(int n)
思路:1.直接用for來放入,不考慮大數問題。
//不考慮大數問題
public int[] printNumbers(int n){
//pow引數是double,返回值也是double
int total = (int)Math.pow(10,n) - 1;
int[] array = new int [total];
for (int i = 0; i < total; i++) {
array[i] = i+1;
}
return array;
}
2.當n變大時,int無法儲存,所以這是一個大數問題。可以使用遞迴dfs(int index)來生成全排列(如0-99),這樣放到char[]裡就可以解決大數問題。
生成全排列用char[] c = {‘0’,‘1’…‘9’}每一位放到char[] num裡,配合遞迴dfs(0),能夠先在個位先從0到9,這樣正好符合數字遞增的規律。(所以有很多類的屬性變數)
class Solution {
private int[] res = null;
private char[] num = null;
private char[] c = {'0','1','2','3','4','5','6','7','8','9'};
private int count = 0;
private int total = 0;
//當n很大時無法處理,所以考慮大數問題(面試時說,說思路,遞迴實現全排列)
public int[] printNumbers(int n) {
num = new char[n];
total = (int)Math.pow(10,n)-1;
res = new int[total];
dfs(0);
return res;
}
//用遞迴來做全排列(為什麼用遞迴?因為生成一位後剩下位都是一樣生成)
//x為char[]的下標
public void dfs(int x){
//x等於n時結束
if(x == num.length){
//整個num是結果,從1開始放
//遇到resItem為0時就跳過,正好與res[]的長度匹配
int resItem = Integer.parseInt(String.valueOf(num));
if(resItem > 0){
res[count] = resItem;
count++;
}
return;
}
for (char item : c) {
num[x] = item;
//x等於n-1時就從'0'賦值到'9',也就是從個位開始,正好符合遞增規律
dfs(x+1);
}
}
}
注意:返回為int[]型別,其實就沒有必要是考慮大數問題,由於面試時會考察大數問題,所以這個思路和這種實現方式要會。