C++ simple recursive algorithm (very short)


  • 0
    M

    recursive algorithm:
    from question we know when n==k that we use string which is the result of n-1,so it can be written in recursive algorithm.
    my code:

    string countAndSay(int n) {
        if (n==1){
            return string("1");
        }else{
            string result = countAndSay(n-1);
            string newresult = "";
            for (int i=0;i<result.length();){
                int j=i+1;
                while(result[i]==result[j] && j<result.length()){
                    j++;
                }
                newresult.append(to_string(j-i));
                newresult.append(to_string(int(result[i]-'0')));
                i=j;
            }
            return newresult;
        }
    }
    

Log in to reply
 

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