注册一亩三分地论坛,查看更多干货!
您需要 登录 才可以下载或查看附件。没有帐号?注册账号
x
首先吐槽下。。。刷到110+,hard的题大部分都没思路了。。。有时还会发生做过的题再打开还是得想好久的情况。。。有没有人能帮忙给点建议。
这个题目,自己是用一个二维数组纪录是否为pal同时,从后往前不断更新每一个字母到末尾的字符串的需要的最小cut数。。。然后看了discuss,有一个方法只用o(n) space, 看了好久没看懂原理,能不能请大家帮忙分析下,谢谢了。
题目要求如下:
Given a string s, partition s such that every substring of the partition is a palindrome. Return the minimum cuts needed for a palindrome partitioning of s. For example, given s = "aab",
Return 1 since the palindrome partitioning ["aa","b"] could be produced using 1 cut.
代码如下:不知道它是怎么来更新cut[]的。。。- class Solution {
- public:
- int minCut(string s) {
- int n = s.size();
- vector<int> cut(n+1, 0); // number of cuts for the first k characters
- for (int i = 0; i <= n; i++) cut[i] = i-1;
- for (int i = 0; i < n; i++) {
- for (int j = 0; i-j >= 0 && i+j < n && s[i-j]==s[i+j] ; j++) // odd length palindrome
- cut[i+j+1] = min(cut[i+j+1],1+cut[i-j]);
- for (int j = 1; i-j+1 >= 0 && i+j < n && s[i-j+1] == s[i+j]; j++) // even length palindrome
- cut[i+j+1] = min(cut[i+j+1],1+cut[i-j+1]);
- }
- return cut[n];
- }
- };
复制代码 不知道正不正常啊,第一次刷题,感觉很难啊,自己又贪玩。。。经常一天只能做三道题。。。主要是很多hard的题没思路。。。不知道是不是因为自己转专业,没系统学习的原因,还有些虽然做出来,总感觉是碰巧,没有说能达到,碰到题目,能分类题目,选择不同方法(如dfs,bfs,dp..)的阶段,特别是recursive的题目,对递归的理解和运用还是不清晰,请大家给点建议
|