lintcode 1884 n = arr.length dp[i][j] 代表拿走
i
~
j
i \sim j
i~j瓶子所需要的最少次数. 初始化条件
-
f
o
r
?
i
=
0
:
n
?
1
f
o
r
?
j
=
i
:
n
?
1
:
for \ i = 0:n-1 \quad for \ j = i:n-1 :
for?i=0:n?1for?j=i:n?1:
dp[i][j] = n -
f
o
r
?
i
=
0
:
n
?
1
:
for \ i = 0:n-1 :
for?i=0:n?1:
dp[i][i] = 1 -
f
o
r
?
i
=
1
:
n
?
1
:
for \ i = 1:n-1 :
for?i=1:n?1:
dp[i-1][i] = 1
i
f
?
a
r
r
[
i
?
1
]
=
a
r
r
[
i
]
if \ arr[i-1]=arr[i]
if?arr[i?1]=arr[i], dp[i-1][i] = 2
i
f
?
a
r
r
[
i
?
1
]
≠
a
r
r
[
i
]
if \ arr[i-1]\neq arr[i]
if?arr[i?1]=arr[i] 状态转移 -
f
o
r
?
l
=
2
:
n
?
1
f
o
r
?
i
=
0
:
n
?
1
,
j
=
i
+
l
:
for \ l = 2:n-1 \quad for \ i = 0:n-1, j=i+l:
for?l=2:n?1for?i=0:n?1,j=i+l:
dp[i][j] = dp[i+1][j-1]
i
f
?
a
r
r
[
i
]
=
a
r
r
[
j
]
if \ arr[i] = arr[j]
if?arr[i]=arr[j] -
f
o
r
?
k
=
i
:
j
?
1
:
for \ k = i:j-1:
for?k=i:j?1:
dp[i][j] = min(dp[i][j],dp[i][k]+dp[k+1][j]))
Java
public class Solution {
public int takeAwayTheBottle(int[] arr) {
int n = arr.length;
int[][] dp = new int[n][n];
for (int i = 0; i < n; i++) {
for (int j = i; j < n; j++) {
if (i == j) dp[i][j] = 1;
else if (i == j-1) {
if (arr[i] == arr[j]) dp[i][j] = 1;
else dp[i][j] = 2;
} else dp[i][j] = n;
}
}
for (int l = 2; l < n; l++) {
for (int i = 0; i < n && i+l < n; i++) {
int j = i+l;
if (arr[i] == arr[j]) dp[i][j] = dp[i+1][j-1];
for (int k = i; k < j; k++) {
dp[i][j] = Math.min(dp[i][j], dp[i][k] + dp[k+1][j]);
}
}
}
return dp[0][n-1];
}
}
Go
func takeAwayTheBottle (arr []int) int {
n := len(arr)
dp := make([][]int,n)
for i,_ := range dp {
dp[i] = make([]int,n)
}
for i := 0; i < n; i++ {
for j := 0; j < n; j++ {
if i == j {
dp[i][j] = 1
} else {
dp[i][j] = n
}
}
}
for i := 0; i+1 < n; i++ {
if arr[i] == arr[i+1] {
dp[i][i+1] = 1
} else {
dp[i][i+1] = 2
}
}
for l := 2; l < n; l++{
for i := 0; i+l < n; i++ {
r := i+l
if arr[i] == arr[r] {
dp[i][r] = dp[i+1][r-1]
}
for k := i; k < r; k++ {
dp[i][r] = min(dp[i][r],dp[i][k]+dp[k+1][r])
}
}
}
return dp[0][n-1]
}
func min(x,y int) int {
if x < y {return x}
return y
}
|