-
Notifications
You must be signed in to change notification settings - Fork 2
Expand file tree
/
Copy pathsolution.cpp
More file actions
48 lines (37 loc) · 1.08 KB
/
Copy pathsolution.cpp
File metadata and controls
48 lines (37 loc) · 1.08 KB
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
class Solution
{
vector<vector<int>> dp;
int solve(int idx, int prevSum, string &s)
{
int n = s.size();
// Reached end -> one valid grouping found
if (idx == n)
return 1;
// Return already computed answer
if (dp[idx][prevSum] != -1)
return dp[idx][prevSum];
int ans = 0;
int currSum = 0;
// Try every possible group starting at idx
for (int end = idx; end < n; end++)
{
// Add current digit to group sum
currSum += s[end] - '0';
// Current group is valid only if sums remain non-decreasing
if (currSum >= prevSum)
{
ans += solve(end + 1, currSum, s);
}
}
// Store result for memoization
return dp[idx][prevSum] = ans;
}
public:
int validGroups(string &s)
{
int n = s.size();
// prevSum can be from 0 to 900
dp.assign(n, vector<int>(901, -1));
return solve(0, 0, s);
}
};