使用回溯进行回文分区的时间复杂度是多少

时间:2018-07-01 05:38:33

标签: c++ algorithm time-complexity recursive-backtracking

给出一个字符串s,分区s,使得分区中的每个字符串都是回文,那么下面的代码的时间复杂度是多少。

bool isPalindrome(string s){
    int i,j;
    for(i=0,j=s.length()-1; i<j && s[i]==s[j]; i++,j--);
    return i>=j;
}
void palindromePartitions(string s, vector<string> ans, vector<vector<string> > &allPartitions, int idx){
    if(s.length()<1)
        return ;
    if(idx == s.length()){
        allPartitions.push_back(ans);
        return;
    }
    string temp;
    for(int i=idx; i<s.length(); i++){
        temp+=s[i];
        ans.push_back(temp);
        if(isPalindrome(temp))
            palindromePartitions(s, ans, allPartitions, i+1);
        ans.pop_back();
    }
}

**//----This is the driver program called from main function----**
vector<vector<string> > Solution::partition(string s) {
    vector<vector<string> > allPartitions;
    if(s.length() < 1)
        return allPartitions;
    vector<string> ans;
    palindromePartitions(s, ans, allPartitions, 0);

    return allPartitions;
}

0 个答案:

没有答案