- dp[i][j]
- i 表示前i个字符
- j 的选择是第i个字符在ring中出现的位置列表。给初始编号
- dp[i][j] =. 所有(dp[i-1][k] + cost(j,k) k可选的这样的值中的最小值
import java.util.ArrayList;
import java.util.List;
class Solution {
int n;
List<Integer>[] index = new ArrayList[26];
int[][] dp;
public int findRotateSteps(String ring, String key) {
n = ring.length();
dp = new int[key.length()][n];
for (int i = 0; i < key.length(); i++) {
int c = key.charAt(i) - 'a';
index[c] = new ArrayList<>();
for (int j = 0; j < n; j++) {
if (ring.charAt(j) == key.charAt(i)) {
index[c].add(j);
}
}
}
for (int i = 0; i < key.length(); i++) {
int c = key.charAt(i) - 'a';
if ( i == 0) {
for (int u : index[c]) {
dp[0][u] = cost(0, u) ;
}
}
else {
for (int u : index[c]) {
dp[i][u] = Integer.MAX_VALUE;
int last = key.charAt(i-1) - 'a';
for (int v : index[last]) {
dp[i][u] = Math.min(dp[i][u], dp[i-1][v] + cost(u,v));
}
}
}
}
int ans = Integer.MAX_VALUE;
int tail = key.charAt(key.length() - 1) - 'a';
for(int u : index[tail]) {
ans = Math.min(dp[key.length()-1][u], ans);
}
return ans;
}
public int cost(int u, int v){
// v 在 12点方向
int x = Math.abs(u-v);
int y = n - x;
return Math.min(x, y) + 1;
}
}
标签:index,charAt,int,length,key,动态,规划,514,dp
From: https://www.cnblogs.com/fishcanfly/p/18221283