- 字典序排数
给你一个整数 n ,按字典序返回范围 [1, n] 内所有整数。
你必须设计一个时间复杂度为 O(n) 且使用 O(1) 额外空间的算法。
示例 1:
输入:n = 13
输出:[1,10,11,12,13,2,3,4,5,6,7,8,9]
示例 2:
输入:n = 2
输出:[1,2]
提示:
1 <= n <= 5 * 104
思想:
按照字典顺序输出数组,从1开始,符合python的sorted函数基本规则:
class Solution:
def lexicalOrder(self, n: int) -> List[int]:
return sorted(range(1,n+1), key=str)
当然这个题不太可能是考察这个函数,应该是考察的递归,或者树的剪枝。
剪枝思想:
首先从1开始,其接下来可能有10,11,…,20之间的数,2也一样,那么可以用一个类似树的处理方式,使用dfs进行递归。
class Solution {
public List<Integer> lexicalOrder( int n) {
List<Integer> res = new ArrayList<>();
for(int i=1;i<10;i++){
if (i>n) {
break;
}
res.add( i );
//深度优先去生成以i开头的字典序数字
dfs(i, n, res);
}
return res;
}
private void dfs( int k, int n, List<Integer> res ) {
for(int i=0;i<10;i++){
int val = k*10 + i;
//如果val>n 则剪枝返回
if (val>n) {
return;
}
res.add( val );
dfs( val, n, res );
}
}
}
作者:wp666
链接:https://leetcode-cn.com/problems/lexicographical-numbers/solution/by-wp666-cnrn/
来源:力扣(LeetCode)
著作权归作者所有。商业转载请联系作者获得授权,非商业转载请注明出处。