美团笔试一二题,只能ac50%(反面教材,已解决)
第一题代码,递归+备忘录:
package interview; import java.util.*; public class Main { static long[][] cache; public static void main(String[] args) { Scanner sc = new Scanner(System.in); int size = sc.nextInt(); sc.nextLine(); cache = new long[2][size]; char[][] places = new char[2][size]; places[0] = sc.nextLine().toCharArray(); places[1] = sc.nextLine().toCharArray(); long ans = walk(2 - 1, size - 1, places); System.out.println(ans == 0 ? - 1 : ans); } public static long walk(int i, int j, char[][] places) { if(i < 0 || j < 0 || i == 2 || j == places[0].length) { return 0; } if(places[i][j] == 'X') { return 0; } if((i == 0 && j == 0)) { return 1; } if(cache[i][j] != 0) { return cache[i][j]; } long n = walk(i, j - 1, places) + walk(i + 1, j - 1, places) + walk(i - 1, j - 1, places); cache[i][j] = n; return n; } }第二题,数组保存结果:
package interview; import java.util.*; public class Main { public static void main(String[] args) { Scanner sc = new Scanner(System.in); int n = sc.nextInt(); int x = sc.nextInt(); int[] nums = new int[n]; for(int i = 0; i<n; i++) { nums[i] = sc.nextInt(); } int[] dp = new int[1001]; for(int i = 0; i<n; i++) { dp[nums[i]] = dp[nums[i]] + 1; if((nums[i] | x) != nums[i]) { dp[nums[i] | x] = dp[nums[i] | x] + 1; } } int ans = 0; for(int i = 0; i<1001; i++) { ans = Math.max(dp[i], ans); } System.out.println(ans); } }