*Maximum Length Palindromic Sub-Sequence of an Array.
2016-01-25 05:14
489 查看
/* Write a function to compute the maximum length palindromic sub-sequence of an array. A palindrome is a sequence which is equal to its reverse. A sub-sequence of an array is a sequence which can be constructed by removing elements of the array. Ex: Given [4,1,2,3,4,5,6,5,4,3,4,4,4,4,4,4,4] should return 10 (all 4's) */ class Interview { public static int maxLengthPalindrome(int[] values) { //ur implementation here }
解法一:
Implemtation is recursive, and it's much worse than O(n^2). Should use recursive with memorization, then can improve to O(n^2).
However, recursive memorization doesn't improve over bottom-up and it has costly overhead. Bottom-up is better in this problem.
public class Solution { public static void main(String[] args) { int arr[] = new int[] {4,1,2,3,4,5,6,5,4,3,4,4,4,4,4,4,4}; System.out.println(maxLengthPalindrome(arr, 0, arr.length-1)); } public static int maxLengthPalindrome(int[] values, int i, int j) { //check if indexes cross each other //return 1 if index overlap for else condition below //return 0 if index i<j for condition if below if(j<=i) return j-i+1; if(values[i]==values[j]) return 2 + maxLengthPalindrome(values, i+1, j-1); else return Math.max(maxLengthPalindrome(values, i+1, j), maxLengthPalindrome(values, i, j-1)); } }
解法二:
The code with the memoization technique which produces O(n^2) complexity is
public int dpLps(int[] a, int i, int j, Integer[][] lps) { if (i > j) return 0; if (lps[i][j] == null) { if (i == j) lps[i][j] = 1; else { if (a[i] == a[j]) lps[i][j] = 2 + dpLps(a, i + 1, j - 1, lps); else lps[i][j] = Math.max(dpLps(a, i + 1, j, lps), dpLps(a, i, j - 1, lps)); } } return lps[i][j]; }
you have to call the function as,
dpLps(a, 0, a.length - 1,new Integer[a.length][a.length])
相关文章推荐
- UIScrollView的属性总结
- HDU-1005 Number Sequence && 51NOD-1126 求递推序列的第N项
- hdoj5501GT and sequence
- DB2创建/修改SEQUENCE
- UIViewController生命周期及方法调用顺序
- UITabelView的分割线处理及介绍
- 设置UITablView的头部试图高度之后···
- 关于UIViewController self.title在IOS7中默认是黑色且字体稍小的解决办法
- 调用EasyUI控件实现下拉框选值切换DataGrid中的记录
- EasyUI 扩展自定义EasyUI校验规则 验证规则(常用的)
- UITableView 介绍
- leetcode300---Longest Increasing Subsequence(最长递增子序列)
- [SGU 532]Building Foundation[几何]
- UISearchController VS UISearchBar and UISearchDisplayController
- zImage与uImage
- php中require 和 include的区别和用法说明
- union-find算法中的quick-find算法的复杂度
- UIAlertController  VS  UIAlertView and UIActionSheet
- Leetcode 52 N-Queens II 回溯搜索
- UEditor去除复制样式实现无格式粘贴