题
思
心乱了
第一题
一看就是弗洛伊德。固定模板,先转成邻接矩阵,自己到自己设为0,不可直达的边设为Integer.MAX_VALUE
.
复制一遍这个邻接矩阵记作floyd
矩阵,三重循环k,i,j。
temp = floyd[i][k] + floyd[k][j]
,如果ik和kj中有不可达的路径,temp仍为不可达。
否则若temp<floyd[i][j],更新floyd[i][j]为temp。
第二题
以前做过。
第三题
没做出来也没时间做了。
dp[i]表示前i个字符能拆成什么几种情况。
dp[i] = dp[i-1] + dp[i-2] + …… +dp[0]
其实最多往前推9步就行了,因为k是有范围的。
代码
第一题
class Solution {
public int findTheCity(int n, int[][] edges, int distanceThreshold) {
int[][] matrix = new int[n][n];
for (int i = 0; i < matrix.length; i++) {
for (int j = 0; j < matrix.length; j++) {
matrix[i][j] = i == j ? 0 : Integer.MAX_VALUE;
}
}
for (int i = 0; i < edges.length; i++) {
matrix[edges[i][0]][edges[i][1]] = edges[i][2];
matrix[edges[i][1]][edges[i][0]] = edges[i][2];
}
int[][] floyd = new int[n][n];
for (int i = 0; i < floyd.length; i++) {
for (int j = 0; j < floyd.length; j++) {
floyd[i][j] = matrix[i][j];
}
}
for (int k = 0; k < floyd.length; k++) {
for (int i = 0; i < floyd.length; i++) {
for (int j = 0; j < floyd.length; j++) {
int temp = (floyd[i][k] == Integer.MAX_VALUE || floyd[k][j] == Integer.MAX_VALUE)
? Integer.MAX_VALUE
: floyd[i][k] + floyd[k][j];
if (floyd[i][j] > temp) {
floyd[i][j] = temp;
}
}
}
}
int min = Integer.MAX_VALUE, minIdx = 0;
for (int i = 0; i < floyd.length; i++) {
int count = 0;
for (int j = 0; j < floyd.length; j++) {
if (j != i && floyd[i][j] <= distanceThreshold) {
count++;
}
}
if (count <= min) {
min = count;
minIdx = i;
}
}
return minIdx;
}
}
第二题
class Solution {
public int largestOverlap(int[][] img1, int[][] img2) {
int len = img1.length;
List<int[]> one1 = new ArrayList<int[]>();
List<int[]> one2 = new ArrayList<int[]>();
for (int i = 0; i < len; i++) {
for (int j = 0; j < len; j++) {
if (img1[i][j] == 1) {
one1.add(new int[] { i, j });
}
if (img2[i][j] == 1) {
one2.add(new int[] { i, j });
}
}
}
int max = 0;
for (int[] pos1 : one1) {
for (int[] pos2 : one2) {
int temp = countOne(pos1, pos2, img1, img2);
max = temp > max ? temp : max;
}
}
return max;
}
private int countOne(int[] pos1, int[] pos2, int[][] img1, int[][] img2) {
int count = 0, len = img1.length;
int rowDelta = -Math.min(pos1[0], pos2[0]), colDelta = -Math.min(pos1[1], pos2[1]);
while (pos1[0] + rowDelta < len && pos2[0] + rowDelta < len) {
while (pos1[1] + colDelta < len && pos2[1] + colDelta < len) {
count += img1[pos1[0] + rowDelta][pos1[1] + colDelta] * img2[pos2[0] + rowDelta][pos2[1] + colDelta];
colDelta++;
}
colDelta = 0;
rowDelta++;
}
return count;
}
}
以下代码参考自这位老哥的题解
第三题
class Solution {
public int numberOfArrays(String s, int k) {
int mod = 1000000007;
int[] dp = new int[s.length() + 1];
dp[0] = 1;
for (int i = 1; i < dp.length; i++) {
for (int j = i - 1; j >= 0 && i - j < 10; j--) {
if (s.charAt(j) == '0') {
continue;
}
if (Long.valueOf(s.substring(j, i)) <= k) {
dp[i] = (dp[i] + dp[j]) % mod;
} else {
break;
}
}
}
return dp[s.length()] % mod;
}
}