Awesome java simple solution


  • 0
    F
        /**
         * 386 Lexicographical Numbers
         *
         * @param n
         * @return
         */
        public List<Integer> lexicalOrder(int n) {
            List<Integer> result = new ArrayList<>();
            for (int i = 1; i <= Math.min(9,n); i++) {
                lexicalOrderDFS(i, n, result);
            }
            return result;
        }
    
        private void lexicalOrderDFS(int start, int bound, List<Integer> result) {
            result.add(start);
            for (int i = 10 * start; i <= Math.min(bound, 10 * start + 9); i++) {
                lexicalOrderDFS(i, bound, result);
            }
        }
    

    following in in scala:

      def lexicalOrder(n: Int) = {
        val result = ListBuffer.empty[Int]
        def dfs(s: Int) {
          result += s
          for (i <- 10 * s to math.min(10 * s + 9, n))
            dfs(i)
        }
        for (i <- 1 to math.min(9, n))
          dfs(i)
        result.toList
      }
    

Log in to reply
 

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.