Advertisement
Singasking

[LeetCode] Decode Ways Problem

Jun 17th, 2023
882
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 0.96 KB | None | 0 0
  1. class Solution {
  2. public:
  3.     bool isValid(string s) {
  4.        
  5.         if(s[0]=='0'){
  6.             return false;
  7.         }
  8.         if(stoi(s)>26) {
  9.             return false;
  10.         }
  11.         return true;
  12.     }
  13.  
  14.     int f(string s, int currentSplit,vector<int> dp){
  15.  
  16.         if(dp[currentSplit]!=-1) {
  17.             return dp[currentSplit];
  18.         }
  19.        
  20.         if(currentSplit==0) { return 1;}
  21.         if(currentSplit<0) { return 0;}
  22.        
  23.         int ans=0;
  24.  
  25.         if(currentSplit>=1 && isValid(s.substr(currentSplit-1,1))){
  26.             ans+=f(s,currentSplit-1,dp);
  27.         }
  28.         if(currentSplit>=2 && isValid(s.substr(currentSplit-2,2))){
  29.             ans+=f(s,currentSplit-2,dp);
  30.         }
  31.         return dp[currentSplit]=ans;
  32.  
  33.  
  34.        
  35.  
  36.     }
  37.     int numDecodings(string s) {
  38.        
  39.          vector<int>dp(s.length()+1,-1);
  40.          return f(s,s.length(),dp);
  41.     }
  42. };
  43.  
  44. //at each position- we can try split or not split
  45.  
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement