Pure Recursion..seems beautiful!


  • 0
    L

    This code seems so readable, intuitive all due to relying on recursion. I feel the purity of technique is kept intact and this is the better way to start correctly coding and then finally tuning it to more optimized while having correctness already taken care of.

     bool ispal(string &s, int i, int e)
    {
        while(i<e )
        {
            if(s[i++] != s[e--])
                return false;
        }
        return true;
        
    }
    void par(vector<vector<string>> &res, string &s, vector<string> &cur, int i=0, int split=0)
    {
    
        if( i== s.length() )
        {
            res.push_back(cur);
            return;
        }
        
        if( split == s.length())
            return;
        
        if(ispal(s,i,split))
        {
            cur.push_back(s.substr(i,split+1-i));
            par(res, s,cur,split+1, split+1);
            cur.pop_back();
        }
        par(res, s, cur, i, split+1);
        
    }
    vector<vector<string>> partition(string s) {
        
        vector<string> cur;
        vector<vector<string>> res;
        res.clear();
        
        par(res,s,cur,0,0);
        return res;
    }

Log in to reply
 

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