您的位置:首页 > 其它

LeetCode - 386. Lexicographical Numbers

2018-07-12 17:13 309 查看

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.

按字典序求所给范围数字列表

回溯,dfs

class Solution {
List<Integer> res;
public List<Integer> lexicalOrder(int n) {
res = new ArrayList<>();
for (int i=1; i<10; i++) {
if (i > n)
break;
dfs(n, i);
}
return res;
}
public void dfs(int n, int cur) {
if (cur > n)
return;
res.add(cur);
for (int i=0; i<10; i++) {
int next = cur * 10 + i;
if (next > n)
return;
dfs(n, next);
}
}
}

 

内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: