386. Lexicographical Numbers

时间:2023-03-09 08:58:39
386. Lexicographical Numbers

用DFS来做,先弄开头是1的,再弄开头是1的里面开头是1的,再开头是1的里面开头是1的里的开头是1的,再。。。

是吧……

比N大了BREAK就行。

注意第一个循环是1-9,往后的循环是0-9。

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