Catalogue
Analysis
Question Type
- Seperate an sequence to several nonoverlapping subarray
- no limit or limited k on the number of the subarray
- Each subarray meet or meet some requirement!
Solution Type
- Normally, dp[i][j]represents previous i elements seperate k subarray
Split Array
410. Split Array Largest Sum
Solution1. DP
- DP[i][j] represents that the largest sum for previous i elements seperated to j group
- DP[i][j] = min{max{dp[k][j-1], sum(k+1, i)}} ($0<= k <i$)
- Time : O($mn^2$), Space : O(mn)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23class Solution:
def splitArray(self, nums, m):
n = len(nums)
# Prefix Sum
preSum = [0]
for i in range(n):
preSum.append(preSum[-1] + nums[i])
dp = [[float('inf')] * m for _ in range(n+1)]
# Init
dp[0][0] = 0
for i in range(n+1):
dp[i][0] = preSum[i]
for j in range(m):
dp[0][j] = 0
# DP
for i in range(1, n+1):
for j in range(i):
for k in range(1, m):
dp[i][k] = min(dp[i][k], max(dp[j][k-1], preSum[i]-preSum[j]))
return dp[-1][-1]
Solution2. Binary Search
1 | class Solution: |
Split String
139. Word Break
Solution1. DFS
- TLE
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15# Worst Case : Time O(n!)
class Solution(object):
def wordBreak(self, s, wordDict):
wset = set(wordDict)
return self.isWordBreak(s, wset)
def isWordBreak(self, s, wset):
if len(s) == 0:
return True
for i in xrange(len(s)):
if s[i:] in wset:
if self.isWordBreak(s[:i], wset):
return True
return False
Solution2. DP
1 | # Time : O(n^2) |
140. Word Break II
- DFS + Memorization
1 | class Solution(object): |
91. Decode Ways
- care about edge cases
1
2
3
4
5
6
7
8
9
10
11
12
13
14class Solution(object):
def numDecodings(self, s):
n = len(s)
dp = [0] * n
dp[0] = 1 if s[0] != '0' else 0
for i in range(1, n):
# case1 : 1 letter
if s[i] != '0':
dp[i] += dp[i-1]
# case2 : 2 letter
if 10 <= int(s[i-1:i+1]) <= 26:
dp[i] += dp[i-2] if i >= 2 else 1
return dp[-1]
639. Decode Ways II
1 | class Solution(object): |
132. Palindrome Partitioning II
- isPalindrome can also use the DP way to solve!!!
1 | class Solution(object): |
410. Split Array Largest Sum
1 | class Solution(object): |