1977. Number of Ways to Separate Numbers
Description
You wrote down many positive integers in a string called num
. However, you realized that you forgot to add commas to seperate the different numbers. You remember that the list of integers was non-decreasing and that no integer had leading zeros.
Return the number of possible lists of integers that you could have written down to get the string num
. Since the answer may be large, return it modulo 109 + 7
.
Example 1:
Input: num = "327" Output: 2 Explanation: You could have written down the numbers: 3, 27 327
Example 2:
Input: num = "094" Output: 0 Explanation: No numbers can have leading zeros and all numbers must be positive.
Example 3:
Input: num = "0" Output: 0 Explanation: No numbers can have leading zeros and all numbers must be positive.
Constraints:
1 <= num.length <= 3500
num
consists of digits'0'
through'9'
.
Solutions
Solution: Dynamic Programming
- Time complexity: O(n2)
- Space complexity: O(n2)
JavaScript
js
/**
* @param {string} num
* @return {number}
*/
const numberOfCombinations = function (num) {
if (num[0] === '0') return 0;
const MODULO = BigInt(10 ** 9 + 7);
const n = num.length;
const dp = Array.from({ length: n }, () => new Array(n + 1).fill(0n));
const lcs = Array.from({ length: n + 1 }, () => new Array(n + 1).fill(0));
for (let a = n - 1; a >= 0; a--) {
for (let b = a + 1; b < n; b++) {
if (num[a] !== num[b]) continue;
lcs[a][b] = lcs[a + 1][b + 1] + 1;
}
}
for (let index = 0; index < n; index++) {
for (let len = 1; len <= index + 1; len++) {
const start = index - len + 1;
dp[index][len] += dp[index][len - 1];
dp[index][len] %= MODULO;
if (num[start] === '0') continue;
if (start === 0) {
dp[index][len] += 1n;
continue;
}
if (start < len) {
dp[index][len] += dp[start - 1][start];
continue;
}
const lc = lcs[start - len][start];
if (lc >= len || num[start - len + lc] <= num[start + lc]) {
dp[index][len] += dp[start - 1][len];
} else {
dp[index][len] += dp[start - 1][len - 1];
}
}
}
return Number(dp[n - 1][n] % MODULO);
};