Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- /*
- QUESTION
- https://www.interviewbit.com/problems/numbers-of-length-n-and-value-less-than-k/
- 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.
- 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.
- */
- #include <bits/stdc++.h>
- using namespace std;
- int formNumber(vector<int> &path){
- int num = 0;
- for(int i = path.size() - 1, base = 0; i >= 0; base++, i--){
- num += path[i] * pow(10, base);
- }
- return num;
- }
- int findNums(vector<int> &path, int len, int &val, vector<int> &nums){
- if(path.size() >= len){
- if(path.size() > 1 && path[0] == 0){
- return 0;
- }
- int number = formNumber(path);
- if(number < val){
- return 1;
- }
- return 0;
- }
- int count = 0;
- for(int i = 0; i < nums.size(); i++){
- path.push_back(nums[i]);
- count += findNums(path, len, val, nums);
- path.pop_back();
- }
- return count;
- }
- int main() {
- // your code goes here
- int n, len, val;
- cin >> n;
- vector<int> nums(n);
- for(int i = 0; i < n; i++){
- cin >> nums[i];
- }
- cin >> len >> val;
- vector<int> path;
- cout << findNums(path, len, val, nums);
- }
Advertisement
Add Comment
Please, Sign In to add comment