leetcode 131. Palindrome Partitioning-回溯算法
来源:互联网 发布:大数据的4v特征是 编辑:程序博客网 时间:2024/06/01 21:36
原题链接:131. Palindrome Partitioning
【思路-Java】递归实现
本题采用回溯算法实现。回溯算法循环和递归相互嵌套,关键是要理清循环中何时递归,何时不进行递归。
我们在最外层循环中判断字符串 s 中的[i,j]是否构成回文。如果构成回文,那么,接着判断s 中 j+1及以后的字符是否构成回文;如果不构成回文,那么就不进行下一次递归,直接在本层循环中判断[i,j+1]是否构成回文:
public class Solution { public List<List<String>> partition(String s) { List<List<String>> res = new ArrayList<>(); dfs(s, res, new ArrayList<String>(), 0); return res; } private void dfs(String s, List<List<String>> res, List<String> temp, int i) { if(i == s.length()) { res.add(new ArrayList<>(temp)); return; } for(int j = i; j < s.length(); j++) { if(isPalindrome(s, i, j)) { //如果[i,j]中字符不构成回文,那么不进行下一次递归,直接进入下一次循环判断[i,j+1] temp.add(s.substring(i,j+1)); dfs(s, res, temp, j+1); //如果[i,j]中字符构成回文,那么进行下一次递归,判断j+1之后字符是否构成回文 temp.remove(temp.size()-1); } } } private boolean isPalindrome(String s, int start, int end) { //判断s中[start,end]字符是否构成回文 while(start < end) if(s.charAt(start++) != s.charAt(end--)) return false; return true; }}22 / 22 test cases passed. Runtime: 6 ms Your runtime beats 67.43% of javasubmissions.
1 0
- leetcode 131. Palindrome Partitioning-回溯算法
- 131. Palindrome Partitioning回溯算法
- LeetCode 131. Palindrome Partitioning--回溯法
- LeetCode 131. Palindrome Partitioning 树形问题,状态回溯
- [leetcode][回溯][DP] Palindrome Partitioning //TODO
- leetcode---Palindrome Partitioning---动规、回溯
- LeetCode 131. Palindrome Partitioning
- [LeetCode]131.Palindrome Partitioning
- [Leetcode] 131. Palindrome Partitioning
- [leetcode] 131.Palindrome Partitioning
- [LeetCode]131. Palindrome Partitioning
- 131. Palindrome Partitioning LeetCode
- Leetcode 131. Palindrome Partitioning
- LeetCode 131. Palindrome Partitioning
- LeetCode *** 131. Palindrome Partitioning
- LeetCode 131. Palindrome Partitioning
- LeetCode-131.Palindrome Partitioning
- 【leetcode】131. Palindrome Partitioning
- Gradle version 2.10 is required. Current version is 2.8.
- C++使用内存库接口示例
- 报错:“App Transport Security has blocked a cleartext HTTP (http://) resource load since it is insecure
- table 固定列和行的实现
- 将var_dump内容保存到文件或者变量中
- leetcode 131. Palindrome Partitioning-回溯算法
- Java加密技术(三)——PBE算法
- Angularjs Config
- 通讯录的原型实现(二)- 类似QQ好友列表实现,分组名悬浮在最顶部
- android开发中常用到的工具类
- 环信(Android)设置头像和昵称的方法(最简单暴力的基于环信demo的集成)。
- 关于iOS block传值的理解
- 表格td内容过多时,td显示省略号,鼠标移入显示全部内容。
- oracle表分区详解