DP17 最少回文切割次数 Palindrome Partitioning @geeksforgeeks

2014-11-24 07:24:46 · 作者: · 浏览: 0

Given a string, a partitioning of the string is a palindrome partitioning if every substring of the partition is a palindrome. For example, “aba|b|bbabb|a|b|aba” is a palindrome partitioning of “ababbbabbababa”. Determine the fewest cuts needed for palindrome partitioning of a given string. For example, minimum 3 cuts are needed for “ababbbabbababa”. The three cuts are “a|babbbab|b|ababa”. If a string is palindrome, then minimum 0 cuts are needed. If a string of length n containing all different characters, then minimum n-1 cuts are needed.

Solution
This problem is a variation of Matrix Chain Multiplication problem. If the string is palindrome, then we simply return 0. Else, like the Matrix Chain Multiplication problem, we try making cuts at all possible places, recursively calculate the cost for each cut and return the minimum value.

Let the given string be str and minPalPartion() be the function that returns the fewest cuts needed for palindrome partitioning. following is the optimal substructure property.

// i is the starting index and j is the ending index. i must be passed as 0 and j as n-1
minPalPartion(str, i, j) = 0 if i == j. // When string is of length 1.
minPalPartion(str, i, j) = 0 if str[i..j] is palindrome.

// If none of the above conditions is true, then minPalPartion(str, i, j) can be 
// calculated recursively using the following formula.
minPalPartion(str, i, j) = Min { minPalPartion(str, i, k) + 1 +
                                 minPalPartion(str, k+1, j) } 
                           where k varies from i to j-1

Following is Dynamic Programming solution. It stores the solutions to subproblems in two arrays P[][] and C[][], and reuses the calculated values.


动态规划一言以蔽之,就是要找最合算的方案


package DP;

public class PalindromePartitioning {

	public static void main(String[] args) {
		String s = "ababbbabbababa";
//		String s = "aa";
		int begin = 0;
		int end = s.length()-1;
//		System.out.println(isPalindromeRec(s, begin, end));
		System.out.println(minPalPartitionDP(s));
		System.out.println(minPalPartitionRec(s, begin, end));
	}
	
	public static boolean isPalindromeRec(String s, int begin, int end){
		if(begin > end){
			return false;
		}
		if(begin == end){
			return true;
		}
		if(end==begin+1 && s.charAt(begin)==s.charAt(end)){
			return true;
		}
		return s.charAt(begin)==s.charAt(end) && isPalindromeRec(s, begin+1, end-1);
	}
	
	public static int minPalPartitionRec(String s, int begin, int end){
		if(begin == end){		// string长度为1时,肯定是,所以无需切割
			return 0;
		}
		if(isPalindromeRec(s, begin, end)){	// 如果s是回文,也无需切割
			return 0;
		}
		int min = Integer.MAX_VALUE;
		for(int k=begin; k