【字符串】38. 外观数列

题目:

解答:

递归+记忆。

class Solution {
public:
    unordered_map<int,string> map;
    string countAndSay(int n) 
    {
        string res;
        if(map.count(n)) 
        {
            return map[n];
        }
        else if(n==1) 
        {
            res="1";
        }
        else if(n==2) 
        {
            res="11";
        }
        else
        {
            string pre=countAndSay(n-1);
            int count = 1;
            for(int i=0;i < pre.size(); i++)
            {
                if(i+1==pre.size()||pre[i]!=pre[i+1]) 
                {
                    res+=(to_string(count)+pre[i]);
                    count=1;
                }
                else 
                {
                    count++;
                }
            }
        }
        map[n]=res;
        return res;
    }
};

猜你喜欢

转载自www.cnblogs.com/ocpc/p/12822677.html