K-th Smallest in Lexicographical Order LeetCode solution in C++
1class Node {2private:3Node *links[10];4bool flag = false;56public:7bool containsKey(int digit) {8return links[digit] != nullptr;9}10void put(int digit, Node *node) {11links[digit] = node;12}13Node *get(int digit) {14return links[digit];15}16bool isEnd() {17return flag;18}19void setEnd() {20flag = true;21}22};2324class Trie {25private:26Node *root;2728public:29Trie() {30root = new Node();31}32void insert(int num) {33string str = to_string(num);34Node *node = root;35for (int i = 0; i < str.length(); i++) {36int digit = str[i] - '0';37if (!node->containsKey(digit)) {38node->put(digit, new Node());39}40node = node->get(digit);41}42node->setEnd();43// stack<int> st;44// while(num) {45// st.push(num%10);46// num /= 10;47// }48// Node* node = root;49// while(!st.empty()) {50// int digit = st.top();51// st.pop();52// if(!node->containsKey(digit)) {53// node->put(digit, new Node());54// }55// node = node->get(digit);56// }57// node->setEnd();58}59int kthELE(int k) {60int ans = 0;61dfs(root, ans, k, 0);62return ans;63}64void dfs(Node *root, int &ans, int &k, int num) {65if (k == 0) return;66if (root->isEnd()) {67ans = num;68k--;69}70for (int i = 0; i <= 9; i++) {71if (root->containsKey(i)) {72dfs(root->get(i), ans, k, num * 10 + i);73}74}75}76};7778class Solution {79public:80int findKthNumber(int n, int k) {81Trie trie;82for (int i = 1; i <= n; i++) trie.insert(i);83return trie.kthELE(k);84}85};