forked from Chayandas07/LeetCode-challenge
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy path1416. Restore The Array
49 lines (47 loc) · 1.43 KB
/
1416. Restore The Array
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
class Solution {
public:
int mod=1000000007;
int solveRec(int ind,string &s,int k){
if(ind==s.size()) return 1;
if(s[ind]=='0') return 0;
long ans=0;
for(int i=ind;i<s.size();i++){
string temp=s.substr(ind,i-ind+1);
if(stoll(temp)<=k) ans+=solveRec(i+1,s,k);
}
return (int)ans%mod;
}
int solveMemo(int ind,string &s,int k,vector<int>&dp){
if(ind==s.size()) return 1;
if(s[ind]=='0') return 0;
if(dp[ind]!=-1) return dp[ind];
long ans=0;
int size=min(ind+to_string(k).size(),s.size());
for(int i=ind;i<size;i++){
string temp=s.substr(ind,i-ind+1);
if(stoll(temp)<=k) ans+=solveMemo(i+1,s,k,dp);
}
return dp[ind]=(int)ans%mod;
}
int solveTabu(string &s,int k){
vector<int>dp(s.size()+1,0);
dp[s.size()]=1;
for(int ind=s.size()-1;ind>=0;ind--){
long ans=0;
if(s[ind]=='0') continue;
int size=min(ind+to_string(k).size(),s.size());
for(int i=ind;i<size;i++){
string temp=s.substr(ind,i-ind+1);
if(stoll(temp)<=k) ans=(ans+dp[i+1])%mod;
}
dp[ind]=(int)ans%mod;
}
return dp[0];
}
int numberOfArrays(string s, int k) {
// return solveRec(0,s,k);
// vector<int>dp(s.size(),-1);
// return solveMemo(0,s,k,dp);
return solveTabu(s,k);
}
};