【DP】回文的最小分割数2

来源:互联网 发布:java学多久可以上岗 编辑:程序博客网 时间:2024/06/05 00:49

要把DP练好!


题目描述

Given a string s, partition s such that every substring of the partition is a palindrome.
Return all possible palindrome partitioning of s.
For example, given s ="aab",
Return
  [
    ["aa","b"],
    ["a","a","b"]
  ]


思路:还是简历ispalin[][]数组,表示从i到k能否构成回文。

然后用DFS遍历ispalin[][]数组,每次遍历都末尾的时候,把收集起来的碎片装进总结果集。

//代码中的排序段代码是因为判题系统需要按字典序输出....贼麻烦

import java.util.*;public class Solution {        public static ArrayList<ArrayList<String>> res;        public ArrayList<ArrayList<String>> partition(String s) {                res = new ArrayList<ArrayList<String>>();        int len = s.length();        boolean [][] ispalin = new boolean [len][len];        for(int i = 0; i < len; ++i){            for(int k = 0; k <=i ; ++k){                if(((i - k) < 2 || ispalin[k+1][i-1])&&(s.charAt(k) == s.charAt(i))){                    ispalin[k][i] = true;                }            }        }        ArrayList<String> temp = new ArrayList<String>();        dfs(len, -1, 0, temp, s, ispalin);        Collections.sort(res, new Comparator<ArrayList < String > >() {            @Override            public int compare(ArrayList<String> o1, ArrayList<String> o2) {                int o1Size = o1.size();                int o2Size = o2.size();                int count = o1Size < o2Size ? o1Size : o2Size;                for (int i = 0; i < count; i++) {                    if (o1.get(i).compareTo(o2.get(i)) != 0) {                        return o1.get(i).compareTo(o2.get(i));                    }                }                return Integer.compare(o1Size, o2Size);            }        });                return res;    }        static void dfs(int len, int index, int col, ArrayList<String> tempres, String s, boolean [][] ispalin){        if(col == len){            ArrayList<String> addres = new ArrayList<String> ();            addres.addAll(tempres);            res.add(addres);        }        for(int i = len - 1; i > index; --i){            if(ispalin[col][i]){                tempres.add(s.substring(col,i+1));                dfs(len, i, i+1, tempres, s, ispalin);                tempres.remove(tempres.size() - 1);;            }        }    }}