-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathCountWaysToBuildGoodStrings.java
More file actions
64 lines (51 loc) · 1.84 KB
/
CountWaysToBuildGoodStrings.java
File metadata and controls
64 lines (51 loc) · 1.84 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
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
package dynamic_programming;
import java.util.HashMap;
import java.util.Map;
/**
* Description: https://leetcode.com/problems/count-ways-to-build-good-strings
* Difficulty: Medium
* Time complexity: O(n)
* Space complexity: O(n)
*/
public class CountWaysToBuildGoodStrings {
// since the answer may be too large, return it modulo 10^9 + 7
private static final int MOD = 1_000_000_007;
public int countGoodStringsViaDP(int low, int high, int zeroes, int ones) {
int[] dp = new int[high + 1];
dp[0] = 1;
for (int length = 1; length <= high; length++) {
int pickZeroes = length >= zeroes ? dp[length - zeroes] : 0;
int pickOnes = length >= ones ? dp[length - ones] : 0;
dp[length] = (pickZeroes + pickOnes) % MOD;
}
int count = 0;
for (int length = low; length <= high; length++) {
count += dp[length];
count %= MOD;
}
return count;
}
public int countGoodStringsViaRecursion(int low, int high, int zeroes, int ones) {
int count = 0;
Map<Integer, Integer> memo = new HashMap<>();
for (int length = low; length <= high; length++) {
count += count(length, zeroes, ones, memo);
count %= MOD;
}
return count;
}
private int count(int length, int zeroes, int ones, Map<Integer, Integer> memo) {
if (memo.containsKey(length)) return memo.get(length);
if (length == 0) return 1; // was able to build string of a given length
int count = 0;
if (length >= zeroes) {
count += count(length - zeroes, zeroes, ones, memo);
}
if (length >= ones) {
count += count(length - ones, zeroes, ones, memo);
}
count %= MOD;
memo.put(length, count);
return count;
}
}