题目:给定长度为n的序列,标签数为m(标签值表示为1,2,....,m),发射概率矩阵E(n * m),其中E[i][j]表示第i个词预测为标签j的发射概率,转移概率矩阵T(m*m),其中T[i][j]为标签i转移到标签j的转移概率。要求返回最优的序列标注结果(一个数组res,res[i]表示第i个词标注的标签值)。
public class Solution {
public int[] getBestPath(int m, int n, double[][] E, double[][] T) {
double[][] dp = new double[n + 1][m + 1];
int[][] his = new int[n + 1][m + 1];
for (int j = 1; j <= m; j++) {
dp[1][j] = E[1][j];
}
for (int i = 2; i <= n; i++) {
for (int j = 1; j <= m ; j++) {
for (int k = 1; k <= m; k++) {
double score = dp[i - 1][k] + T[k][j] + E[i][j];
if (score > dp[i][j]) {
dp[i][j] = score;
his[i][j] = k;
}
}
}
}
int label = 0;
double min = Double.MIN_VALUE;
for (int j = 1; j <= m; j++) {
if (dp[n][j] > min) {
label = j;
min = dp[n][j];
}
}
int[] res = new int[n + 1];
for (int i = n; i >= 1; i--) {
res[i] = label;
label = his[i][label];
}
return res;
}
}
来源:oschina
链接:https://my.oschina.net/u/4317177/blog/3433776