【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);; } } }}
阅读全文
0 0
- 【DP】回文的最小分割数2
- 【DP】回文的最小分割数
- 最小回文分割数 Palindrome Partitioning II
- 字符串问题---回文最小分割数
- 动态规划之回文最小分割数
- 分割成回文需要的最小分割数 Palindrome Partitioning II @LeetCode
- 求回文字符串的最小分割
- LeetCode-----回文串的最小分割
- 回文数、整数输出,数字序列最小分割问题
- 动态规划——回文串最小分割数
- 大于一个数的最小回文数
- 回文最少分割数
- 回文最少分割数
- 回文最少分割数
- 【DP生成回文字符串的最小插入字符数】POJ 1159
- [LeetCode]—Palindrome Partitioning II 回文分割,求最小分割数
- 构成最小回文数的分析
- 大于N的最小回文数
- 2016 校 招
- EmguCV Mat元素访问的方法
- 数据结构 | 中缀表达式-->前后缀表达式
- 二级Web程序设计考试大纲(2013年版)
- DOM节点层次(Node类型)
- 【DP】回文的最小分割数2
- java编程:输入int数组的方法一(不知道长度)
- SpringBoot 配置分析(二)
- FreeRTOS任务基础
- NTT(模板)
- Yii2学习-关于Model总结
- ART深度探索开篇:从Method Hook谈起
- [置顶] Android自定义控件 温度旋转按钮
- 找回path变量值