题目地址:https://leetcode-cn.com/problems/count-and-say/
思路:递归
AC代码:

class Solution {
public:
    string solve(int n){
        string temp =\"\";
        if(n==1)
            return temp+\"1\";
        temp = solve(n-1); 
        temp+=\"#\";
        string ans = \"\";
        int length = temp.length();
        int count = 0;
        char res[105];
        for(int i=0;i<length;i++){
            if(i==0 || temp[i] == temp[i-1])
                count+=1;
            else{
                int j = 0;
                memset(res,0,sizeof(res));
                while(count){
                    int now = count%10;
                    res[j++] = now+\'0\';
                    count = count/10;
                }
                for(int k = 0;k<j/2;k++){
                    char p = res[k];
                    res[k] = res[j-1-k];
                    res[j-1-k] = p;
                }
                res[j] = temp[i-1];
                ans+=(string)res;
                count = 1;
            }
        }
        //cout<<ans<<endl;
        return ans;
    }
    string countAndSay(int n) {
        return solve(n);
    }
};
收藏 打印