-
Notifications
You must be signed in to change notification settings - Fork 2
Expand file tree
/
Copy pathsolution.java
More file actions
46 lines (33 loc) · 1.03 KB
/
Copy pathsolution.java
File metadata and controls
46 lines (33 loc) · 1.03 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
class Solution {
private int[][] dp;
private int solve(int idx, int prevSum, String s) {
int n = s.length();
// Reached end -> one valid grouping
if (idx == n)
return 1;
// Memoized answer
if (dp[idx][prevSum] != -1)
return dp[idx][prevSum];
int ans = 0;
int currSum = 0;
// Try all possible group endings
for (int end = idx; end < n; end++) {
// Update current group sum
currSum += s.charAt(end) - '0';
// Maintain non-decreasing condition
if (currSum >= prevSum) {
ans += solve(end + 1, currSum, s);
}
}
return dp[idx][prevSum] = ans;
}
public int validGroups(String s) {
int n = s.length();
dp = new int[n][901];
// Initialize memo table
for (int i = 0; i < n; i++) {
java.util.Arrays.fill(dp[i], -1);
}
return solve(0, 0, s);
}
}