Given an integer n, return 1- n in lexicographical order.
For example, given, return: [1,10,11,12,13,2,3,4,5,6,7,8,9].
Please optimize your algorithm for use of less time and space. The input size may be as large as 5,000,000.
A problem without labels, the first thought is the depth first search. It is very straightforward to think of 0-9 of the numbers as nodes, each node is attached to 0-9 nodes. This starts the traversal from 0 to 9 (except that the first is from 1 traversal), and each node that encounters it continues to traverse the node of 0-9 that it is connected to until it reaches N. It is very simple and clear to think this problem with the idea of the picture. Directly on the code, opinion law one.
If you use a larger number to observe the order of adding numbers, such as 112, it is not difficult to find some rules. Each time you add a number, the next number always corresponds to several cases (the next number must be smaller than N):
1.10 times times the last number added;
2. Last added number +1;
3. The last number added is divided by 10 (integer division) +1.
At the same time, if all of the three cases are less than n, they are always added in the order above. Take 112 as an example, after adding the number 1 , the case 1, the case 2 of 2, and the case three of 1 are eligible, then you must first add a condition of 1. So, the next number that needs to be added is based on the number of numbers that continue to be generated according to the situation. If condition 1 is not satisfied, naturally add the number generated by case 2. When did that change from situation 2 to situation 3? By observing, the conversion from condition 2 to condition 3 always occurs in single digit 9, or when the last added number is n. After the conversion is complete, continue adding the next number in the order of the conditions.
Summing up the law, as long as the law continuously add n number can. Opinion Act Two.
Solution One (Java)
classSolution { PublicList<integer> Lexicalorder (intN) {List<Integer> res =NewArraylist<>(n); for(inti = 1; I <= 9; i++) { if(i > N) Break; DFS (i, res, n); } returnRes; } Private voidDfsintI, list<integer> res,intN) {res.add (i); for(intm = 0; M <= 9; m++) { if(I * ten + M > N) Break; DFS (i* 10 +m, res, n); } }}
Solution Two (Java)
classSolution { PublicList<integer> Lexicalorder (intN) {List<Integer> res =NewArraylist<>(n); Res.add (1); intPre = 1; for(inti = 1; I < n; i++) { if(PRE * <= N) Pre *= 10; Else { while(Pre% = = 9 | | pre = n) Pre/= 10; Pre++; } res.add (pre); } returnRes; }}
(Java) Leetcode 386. Lexicographical numbers--dictionary number of sequential rows