动态规划面试题型归类机

1. 路径数目问题

• 1.1. 一维路径数目
题目概述



$f(n)= \begin{cases} 1 & n=1 \2 & n=2 \f(n-1) + f(n-2) & n>2 \end{cases}$

• 1.2. 二维路径数目
题目概述


def uniquePathsWithObstacles(self, obstacleGrid):
# type obstacleGrid: List[List[int]]
row = len(obstacleGrid)
col = len(obstacleGrid[0])
dp = [[1] * col for i in range(row)]
for i in range(0, row):
for j in range(0, col):
if obstacleGrid[i][j]: # 如果这个点是障碍
dp[i][j] = 0
elif i == 0:
dp[i][j] = dp[i][j-1]
elif j == 0:
dp[i][j] = dp[i-1][j]
else:
dp[i][j] = dp[i-1][j] + dp[i][j-1]
return dp[-1][-1]

• 1.3. 串路径数目
题目概述
‘A‘到‘Z‘用数字1~26表示
Input: "12"
Output: 2
12可以有两种编码方式 "AB" (1 2) or "L" (12).


def numDecodings(self, s):
if len(s)==0 or s[0]==‘0‘: return 0
dp = [1,1]
for i in range(2, len(s)+1):
if s[i-2:i]==‘10‘ or s[i-2:i]==‘20‘:
dp.append(dp[i-2])
elif 10<int(s[i-2:i])<=26:
dp.append(dp[i-1]+dp[i-2])
elif s[i-1]!=‘0‘:
dp.append(dp[i-1])
else:
return 0
return dp[-1]


2. 路径耗费问题

• 2.1. 二维路径耗费
题目概述



$dp[row][col] = min(dp[row][col-1], dp[row-1][col]) + matrix[row][col]$

题目概述
[
[2],
[3,4],
[6,5,7],
[4,1,8,3]
]



$dp[row][i] = min(dp[row+1][i], dp[row+1][i+1]) + triagnle[row][i]$

3. 数字拆分问题

• 2.1. 求拆分数目
题目概述
Input: n = 13
Output: 2
Explanation: 13 = 4 + 9.



$dp[n] = min(dp[n-s]+1), \ \ s \in 1,4,9,16,...$

int numSquares(int n) {
int *dp = new int[n + 1];
dp[0] = 0;
for (int i=1; i<=n; i++) {
int _min = INT_MAX;
for (int j=1; j*j<=i; j++) {
_min = min(_min, dp[i-j*j]+1);
}
dp[i] = _min;
}
delete[]dp;
return dp[n];
}


(0)
(0)