码迷,mamicode.com
首页 > 其他好文 > 详细

*Maximum Length Palindromic Sub-Sequence of an Array.

时间:2016-01-25 06:38:13      阅读:200      评论:0      收藏:0      [点我收藏+]

标签:

 

/* 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])

 

*Maximum Length Palindromic Sub-Sequence of an Array.

标签:

原文地址:http://www.cnblogs.com/hygeia/p/5156497.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!