Fastrail08

Digit DP intuitive approach - QUESTION (numbers of length N and value < k)

Aug 17th, 2025
231
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 1.51 KB | None | 0 0
  1. /*
  2. QUESTION
  3. https://www.interviewbit.com/problems/numbers-of-length-n-and-value-less-than-k/
  4.  
  5. This question if written recursively uses permutation to generate answers similar to interval DP questions, which means there must be another optimal way to solve the same problem. That method is through Digit DP.
  6. NOICE - both interval dp & digit dp recognized why traditional way of recursing(via permutation) will not work, as we know permutation generating code can't be memoised, because each path in the tree is unique, so no overlap.
  7. */
  8. #include <bits/stdc++.h>
  9. using namespace std;
  10.  
  11.  
  12. int formNumber(vector<int> &path){
  13.     int num = 0;
  14.     for(int i = path.size() - 1, base = 0; i >= 0; base++, i--){
  15.         num += path[i] * pow(10, base);
  16.     }
  17.     return num;
  18. }
  19.  
  20.  
  21.  
  22. int findNums(vector<int> &path, int len, int &val, vector<int> &nums){
  23.     if(path.size() >= len){
  24.         if(path.size() > 1 && path[0] == 0){
  25.             return 0;
  26.         }
  27.         int number = formNumber(path);
  28.        
  29.         if(number < val){
  30.             return 1;
  31.         }
  32.         return 0;
  33.     }
  34.     int count = 0;
  35.     for(int i = 0; i < nums.size(); i++){
  36.         path.push_back(nums[i]);
  37.         count += findNums(path, len, val, nums);
  38.         path.pop_back();
  39.     }
  40.     return count;
  41. }
  42.  
  43.  
  44. int main() {
  45.     // your code goes here
  46.     int n, len, val;
  47.     cin >> n;
  48.     vector<int> nums(n);
  49.     for(int i = 0; i < n; i++){
  50.         cin >> nums[i];
  51.     }
  52.     cin >> len >> val;
  53.     vector<int> path;
  54.     cout << findNums(path, len, val, nums);
  55. }
  56.  
Advertisement
Add Comment
Please, Sign In to add comment