Distinct Subsequences II — LeetCode 940 Python Solution
HardStringDynamic Programming
- Problem
- #940
- Pattern
- Dynamic Programming
- Reading time
- 2 min
- Source
- leetcode.com
The problem
Given a string s, return the number of distinct non-empty subsequences of s. Since the answer may be very large, return it modulo 109 + 7.
Example
- Input
- s = "abc"
- Output
- 7
- Explanation
- The 7 distinct subsequences are "a", "b", "c", "ab", "ac", "bc", and "abc".
Python solution
Python
class Solution:
def distinctSubseqII(self, s: str) -> int:
mod = 10**9 + 7
n = len(s)
dp = [[0] * 26 for _ in range(n + 1)]
for i, c in enumerate(s, 1):
k = ord(c) - ord('a')
for j in range(26):
if j == k:
dp[i][j] = sum(dp[i - 1]) % mod + 1
else:
dp[i][j] = dp[i - 1][j]
return sum(dp[-1]) % modComplexity
| Measure | Complexity |
|---|---|
| Time | O(n·m) (typical) |
| Space | O(n·m) or optimized auxiliary |
Pattern: Dynamic Programming
Define a state, write the transition, and stop recomputing the same subproblem. LeetCode 940. Distinct Subsequences II is filed here on both counts: the reference solution below belongs to the algorithm family this hub collects, and LeetCode tags it Dynamic Programming.
The dynamic programming guide has the Python template for the pattern and the 481 LeetCode problems that use it.
Related problems
Frequently asked questions
- How hard is LeetCode 940. Distinct Subsequences II?
- LeetCode 940. Distinct Subsequences II is rated Hard on LeetCode.
- What topics does LeetCode 940. Distinct Subsequences II cover?
- LeetCode 940. Distinct Subsequences II is tagged String and Dynamic Programming on LeetCode.