LeetCode–列印從1到最大的n位數
阿新 • • 發佈:2020-09-10
LeetCode–列印從1到最大的n位數
部落格說明
文章所涉及的資料來自網際網路整理和個人總結,意在於個人學習和經驗彙總,如有什麼地方侵權,請聯絡本人刪除,謝謝!
介紹
題目
輸入數字 n,按順序打印出從 1 到最大的 n 位十進位制數。比如輸入 3,則打印出 1、2、3 一直到最大的 3 位數 999。
示例 1:
輸入: n = 1
輸出: [1,2,3,4,5,6,7,8,9]
說明:
用返回一個整數列表來代替列印
n 為正整數
程式碼
class Solution { public int[] printNumbers(int n) { int num = (int)Math.pow(10,n) - 1; int[] res = new int[num]; for(int i = 0; i < num; i++){ res[i] = i+1; } return res; } }
大數列印
class Solution { int[] res; int nine = 0, count = 0, start, n; char[] num, loop = {'0', '1', '2', '3', '4', '5', '6', '7', '8', '9'}; public int[] printNumbers(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; } 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--; } }
感謝
Leetcode