Advertisement
blwrvksrblv

386. Lexicographical Numbers

Feb 19th, 2019
91
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Java 0.67 KB | None | 0 0
  1. class Solution {
  2.     public List<Integer> lexicalOrder(int n) {
  3.         List<Integer> result = new ArrayList<>();
  4.         if (n <= 0) {
  5.             return result;
  6.         }
  7.        
  8.         for (int i=1; i<10; i++) {
  9.             dfs(i, n, result);
  10.         }
  11.        
  12.         return result;
  13.     }
  14.    
  15.     public void dfs(int cur, int n, List<Integer> res) {
  16.         if (cur > n) {
  17.             return;
  18.         }
  19.        
  20.         res.add(cur);
  21.         for (int i=0; i<10; i++) {
  22.             int newCur = cur*10 + i;
  23.            
  24.             if (newCur > n) {
  25.                 return;
  26.             }
  27.            
  28.             dfs(newCur, n, res);
  29.         }
  30.     }
  31. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement