
[抄题]:
Given an integer n, return 1 - n in lexicographical order.
For example, given 13, return: [1,10,11,12,13,2,3,4,5,6,7,8,9].
Please optimize your algorithm to use less time and space. The input size may be as large as 5,000,000.
[暴力解法]:
时间分析:
空间分析:
[优化后]:
时间分析:
空间分析:
[奇葩输出条件]:
[奇葩corner case]:
cur * 10 + i 进位时>n就退出
[思维问题]:
不知道怎么做dfs:多开几个变量,用cur记录当前可以进位的数,0-9,加i,也0-9.
[英文数据结构或算法,为什么不用别的数据结构或算法]:
lexico举例时,就是for 0-9就行了
[一句话思路]:
[输入量]:空: 正常情况:特大:特小:程序里处理到的特殊情况:异常情况(不合法不合理的输入):
[画图]:
[一刷]:
- 可用于递归的数字记录为cur, 从1开始
[二刷]:
- 同一个dfs中的n和i是不变的。i变化时return换i, cur变化时return换cur。(在谁的主场return就换谁)
[三刷]:
- dfs写得不熟悉啊:先添加,再进行下一步扩展,而且dfs中要写传递的公式
[四刷]:
[五刷]:
[五分钟肉眼debug的结果]:
不懂哪里错,究其原因还是对dfs不熟悉
[总结]:
[复杂度]:Time complexity: O() Space complexity: O(n)
[算法思想:迭代/递归/分治/贪心]:
[关键模板化代码]:
public void dfs(int cur, int n, List<Integer> result) {
//exit when cur > n
if (cur > n) return; //add the cur
result.add(cur);
//i loop from 0-9, go further dfs
for (int i = 0; i <= 9; i++) {
//exceed when new number > n
if (10 * cur + i > n)
return ;
dfs(10 * cur + i, n, result);
}
}
[其他解法]:
[Follow Up]:
[LC给出的题目变变变]:
[代码风格] :
[是否头一次写此类driver funcion的代码] :
[潜台词] :
class Solution {
public List<Integer> lexicalOrder(int n) {
//initialization
List<Integer> result = new ArrayList<Integer>(); //corner case
if (n <= 0) return result; //for loop for cur
for (int cur = 1; cur <= 9; cur++) {
dfs(cur, n, result);
} //return
return result;
} public void dfs(int cur, int n, List<Integer> result) {
//exit when cur > n
if (cur > n) return; //add the cur
result.add(cur);
//i loop from 0-9, go further dfs
for (int i = 0; i <= 9; i++) {
//exceed when new number > n
if (10 * cur + i > n)
return ;
dfs(10 * cur + i, n, result);
}
}
}