Lexicographical Numbers

来源:互联网 发布:紫砂壶店铺淘宝排名 编辑:程序博客网 时间:2024/05/29 07:56
import java.util.ArrayList;import java.util.List;/* * 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. *  * if n=2000 * 1,10,100,1000,1001,1002,1003......1009,101,1010,1011,1012.......1019,102,1020,1021.....,11,110,1100,1101.. * */public class Solution {public static void main(String[] args) {// TODO Auto-generated method stub}public List<Integer> lexicalOrder(int n) {        List<Integer> res = new ArrayList<>();        if(n == 0)        return res;        for(int i = 1; i < 10; ++i)        {        dfs(i,res,n);        }        return res;    }public void dfs(int cur,List<Integer> res,int n){if(cur > n)return;res.add(cur);for(int i = 0; i < 10; ++i){if(cur * 10 + i <= n){dfs(cur * 10 + i,res,n);}elsebreak;}}}

0 0