Lexicographical Numbers - Medium - L

less than 1 minute read

Published:

Question

  • https://leetcode.com/problems/lexicographical-numbers/

Given an integer n, return all the numbers in the range [1, n] sorted in lexicographical order.

Approach

  • DFS

Solution

class Solution {
public:
    void dfs(int i,int n,vector<int>&ans)
    {
        if(i>n) return;
        ans.push_back(i);
        for(int j=0;j<10;j++)
        {
            int d=i*10+j;
            if(d<=n)
            dfs(d,n,ans);
        }
    }
    vector<int> lexicalOrder(int n) {
      vector<int>ans;
      for(int i=1;i<10;i++)
          dfs(i,n,ans);
      return ans;
    }
};