public static int longestPalindromeSubseq(String s) {
if (s == null) return 0;
int len = s.length();
char[] chs = s.toCharArray();
int[] dp = new int[len];
Arrays.fill(dp, 1);
int max = 0;
for (int i = len - 1; i >= 0; i--) {
char cur = chs[i];
int curMax = 0;
for (int j = i + 1; j < len; j++) {
int mem = dp[j];
if (cur == chs[j]) {
dp[j] = curMax + 2;
}
curMax = Math.max(mem, curMax);
}
}
for (int e: dp) max = Math.max(max, e);
return max;
}
public static int countSubstrings2(String s) {
int res = s.length();
char[] cs = s.toCharArray();
for(int i=0;i<cs.length;i++){
int left = i-1,right=i+1; while(left>=0&&right<cs.length&&cs[right]==cs[left]){
res++;left--;right++;
}
left = i;right = i+1; while(left>=0&&right<cs.length&&cs[right]==cs[left]){
res++;left--;right++;
}
}
return res;
}
public int rob(int[] nums) {
int[] res = new int[nums.length];
for (int i=0;i<nums.length;i++){
res[i] = nums[i];
if (i>0) res[i] = Math.max(res[i-1],res[i]);
if (i>1) res[i] = Math.max(nums[i]+res[i-2],res[i]);
if (i>2) res[i] = Math.max(nums[i]+res[i-3],res[i]);
}
return res[nums.length-1];
}
public int rob(int[] nums) {
if (nums.length == 1) return nums[0];
if (nums.length == 0) return 0;
return Math.max(getRob(nums, 0, nums.length - 2), getRob(nums, 1, nums.length - 1));
}
public int getRob(int[] nums, int start, int end) {
int[] res = new int[nums.length];
for (int i = start; i <= end; i++) {
res[i] = nums[i];
if (i > 0) res[i] = Math.max(res[i - 1], res[i]);
if (i > 1) res[i] = Math.max(nums[i] + res[i - 2], res[i]);
}
return res[end];
}
public int rob(TreeNode root) {
int[] dp = dp(root);
return Math.max(dp[0], dp[1]);
}
public int[] dp(TreeNode root) {
if (root == null) return new int[]{0, 0};
if (root.left == null && root.right == null) {
return new int[]{root.val, 0};
}
int[] dp = new int[2];
int[] left = dp(root.left);
int[] right = dp(root.right);
dp[0] = root.val + left[1] + right[1];
dp[1] = Math.max(left[1],left[0]) + Math.max(right[1],right[0]);
return dp;
}
public int nthSuperUglyNumber(int n, int[] primes) {
int[] dp = new int[n];
int k = primes.length;
int[] p = new int[k];
dp[0] = 1;
for (int i = 1; i < n; i++) {
int min = Integer.MAX_VALUE;
int minBase = 0;
for (int j = 0; j < k; j++) {
int candidate = dp[p[j]] * primes[j];
if (candidate == min) {
p[j]++;
continue;
}
if (candidate < min) {
min = candidate;
minBase = j;
}
}
dp[i] = min;
p[minBase]++;
}
return dp[n - 1];
}
|