How to deal with the time limit problems in my c++ recursive code


  • 0
    D

    class Solution {
    public:

    bool isInterleave(string s1, string s2, string s3) {
    if(s3.empty()){
    
        if(s1.empty()){
            if(s2==""){
                return true;
            }
        }
        
        if(s1==""){
            if(s2.empty()){
                return true;
            }
        }
        if(s1==s2&&s2==""){
            return true;
        }
    
        if(!s1.empty()||!s2.empty()){
            return false;
        }
    }
    
    
    
    
    if(s1[0]==s3[0]){
        string temp1(s1.begin()+1,s1.end());
        string temp3_1(s3.begin()+1,s3.end());
        
        if(isInterleave(temp1,s2,temp3_1)){
            return true;
        }
    }
    
    
    if(s2[0]==s3[0]){
        string temp2(s2.begin()+1,s2.end());
        string temp3_2(s3.begin()+1,s3.end());
        if(isInterleave(s1,temp2,temp3_2)){
            return true;
        }
    }
    

    // cout<<"end"<<endl;
    return false;

    }
    

    };


  • 0
    A

    your codes are O(2^n) at least, there are many Repeating States here. at this program, dp is the best solution


Log in to reply
 

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.