第二题:给你一串由小写字母构成的字符串,若字符串中两个字符相同,你可以将其标记并得分,得分为两个字符在字母表中的位置(从1开始)之和;若两个字符在字母表中相邻,也可以将其标记,例如ab相邻,yx相邻。每个字符只能被标记一次,返回所能取得的最高分。
import java.util.*; public class Main { public static void main(String[] args) { Scanner sc = new Scanner(System.in); String s = sc.nextLine(); int n = s.length(); if (n < 2) { System.out.println(0); return; } // dp[i]表示以i为结尾的最大贡献 int[] dp = new int[n]; dp[0] = 0; dp[1] = cal(s.charAt(0), s. charAt(1)); for (int i = 2; i < n; i++) { dp[i] = Math.max(dp[i-2] + cal(s.charAt(i-1), s.charAt(i)), dp[i-1]); } System.out.println(dp[n-1]); } public static int cal(char a, char b) { int x = a - 'a' + 1; int y = b - 'a' + 1; if (Math.abs(x-y) <= 1) { return x + y; } return 0; } }
第三题:给你一个数字n,让你将数字1-n填入完全二叉树,要求除根节点外,每个节点值与父节点值的乘积是偶数。
import java.util.*; public class Main { public static void main(String[] args) { Scanner sc = new Scanner(System.in); int n = sc.nextInt(); System.out.print(2); for (int i = 4; i <= n; i += 2) { System.out.print(" " + i); } for (int i = 1; i <= n; i += 2) { System.out.print(" " + i); } } }
第四题:二维dp 求 左上角 到 右下角的最短路径 平原到平原、沼泽到沼泽的cost为1;平原到沼泽和沼泽到平原的cost为2
// 二维dp 向下 向右走即可
import java.util.*; public class Main { public static void main(String[] args) { Scanner sc = new Scanner(System.in); int n = sc.nextInt(), m = sc.nextInt(); int[][] board = new int[n][m]; for (int i = 0; i < n; i++) { for (int j = 0; j < m; j++) { board[i][j] = sc.nextInt(); } } int[][] dp = new int[n][m]; dp[0][0] = 0; for (int i = 1; i < n; i++) { if (board[i][0] == board[i-1][0]) { dp[i][0] = dp[i-1][0] + 1; } else { dp[i][0] = dp[i-1][0] + 2; } } for (int j = 1; j < m; j++) { if (board[0][j] == board[0][j-1]) { dp[0][j] = dp[0][j-1] + 1; } else { dp[0][j] = dp[0][j-1] + 2; } } for (int i = 1; i < n; i++) { for (int j = 1; j < m; j++) { dp[i][j] = Math.min(dp[i-1][j] + (board[i-1][j] == board[i][j]? 1: 2), dp[i][j-1] + (board[i][j-1] == board[i][j]? 1: 2)); } } System.out.println(dp[n-1][m-1]); } }