由买买提看人间百态

boards

本页内容为未名空间相应帖子的节选和存档,一周内的贴子最多显示50字,超过一周显示500字 访问原贴
JobHunting版 - 请教一个leetcode time complexity,Palindrome Partitioning
相关主题
请教一个Palindrome Partition问题有人同看Longest Palindromic Substring 这道题么?
leetcode里的Palindrome partition问题星期一福利:某公司店面题
Palindrome Partitioning II 的DP做法?Leetcode的Substring with Concatenation of All Words超时。
问问 leetcode 新题谁能猜猜,这是个什么 algorithm?
请教道算法题leetcode Parlindrome Partition run time error
问道老题Leetcode Scramble String简单解法
leetcode online judge Longest Palindromic Substring memory limit exceeded问一道最近的onsite题
Memory Limit Exceeded: Longest Palindromic Substringhow to resolve this question?
相关话题的讨论汇总
话题: string话题: curresult话题: index话题: list
进入JobHunting版参与讨论
1 (共1页)
w*******1
发帖数: 32
1
原题在这:
https://oj.leetcode.com/problems/palindrome-partitioning/
根据结果分析猜是O(n*2^n),但是不会从代码分析。请教各位大牛,如果用以下代码,
怎么分析复杂度?
public void palindromeHelper(String input, List> resultList
, List curResult, int index){

if(index == input.length()){
resultList.add(new ArrayList(curResult));
return;
}
for(int i=index; i String substring = input.substring(index, i+1);
if(isPalindrome(input, index, i)){
curResult.add(substring);
palindromeHelper(input, resultList, curResult, i+1);
curResult.remove(curResult.size()-1); }
}
}
call with: palindromeHelper(s, resultList, curResult, 0);
isPalindrome()代码就不附了,最简单O(n)那种。
多谢!!
t*******y
发帖数: 22
2
last character will be accessed n times; last second character will be
accessed n-1 times. the complexity is n+(n-1)+(n-2)+...1=O(n^2)
since you isPalindrome takes O(n), total will be O(n^3).
if you calculate isPlaindrome first, it takes O(n^2); in your recursive
function, it will take O(1) to call that function. overall complexiy will be
O(n^2).
w*******1
发帖数: 32
3
多谢!!
但是从结果来看,一个长度为N的string,partition的结果个数为2^(N-1),相当于把N-
1个挡板插入N个字符里:
string: 1234
C30: 1234
C31: 1|234, 12|34, 123|4
C32: 1|2|34, 1|23|4, 12|3|4
C33: 1|2|3|4
C30 + C31 + C32 + C33 = 2^3
所以不考虑isPalindrom的影响,复杂度应该不低于O(2^N)

be

【在 t*******y 的大作中提到】
: last character will be accessed n times; last second character will be
: accessed n-1 times. the complexity is n+(n-1)+(n-2)+...1=O(n^2)
: since you isPalindrome takes O(n), total will be O(n^3).
: if you calculate isPlaindrome first, it takes O(n^2); in your recursive
: function, it will take O(1) to call that function. overall complexiy will be
: O(n^2).

t*******y
发帖数: 22
4
i think you are right.
1 (共1页)
进入JobHunting版参与讨论
相关主题
how to resolve this question?请教道算法题
on-site的时候Trie和suffix tree会考coding吗?问道老题
问道算法题leetcode online judge Longest Palindromic Substring memory limit exceeded
leetcode上的Longest Palindromic Substring难道不收brute for Memory Limit Exceeded: Longest Palindromic Substring
请教一个Palindrome Partition问题有人同看Longest Palindromic Substring 这道题么?
leetcode里的Palindrome partition问题星期一福利:某公司店面题
Palindrome Partitioning II 的DP做法?Leetcode的Substring with Concatenation of All Words超时。
问问 leetcode 新题谁能猜猜,这是个什么 algorithm?
相关话题的讨论汇总
话题: string话题: curresult话题: index话题: list