classSolution { char res[]; public String largestPalindrome(int n, int k) { res = newchar[n]; // MOD[i]: 10^i % k int MOD[] = newint[n+1]; MOD[0] = 1 % k; for (inti=0; i < n; i++) { MOD[i+1] = (MOD[i] * 10) % k; } int vis[][] = newint[(n+1)/2][10]; dfs(0, 0, n, k, MOD, vis); returnnewString(res); } // i:当前数位,mod:当前数字mod k的余数 publicbooleandfs(int i, int mod, int n, int k, int MOD[], int vis[][]) { if (i >= (n+1)/2) return mod == 0; if (vis[i][mod] == 1) returnfalse; for (intj=9; j >= 0; j--) { booleanmid= n % 2 == 1 && i == n/2; intnext=0; if (mid) next = (mod + MOD[i]*j) % k; else next = (mod + (MOD[i]+MOD[n-1-i])*j) % k; if (dfs(i+1, next, n, k, MOD, vis)) { res[i] = (char)(j+48); res[n-1-i] = (char)(j+48); returntrue; } } vis[i][mod] = 1; returnfalse; } }