> For the complete documentation index, see [llms.txt](https://dfine.gitbook.io/leetcode/llms.txt). Markdown versions of documentation pages are available by appending `.md` to page URLs; this page is available as [Markdown](https://dfine.gitbook.io/leetcode/38.count_and_say.md).

# 38.Count and Say

**38.Count and Say**

难度:Easy

> 报数序列是一个整数序列，按照其中的整数的顺序进行报数，得到下一个数。其前五项如下：

1. ```
   1
   ```
2. ```
   11
   ```
3. ```
   21
   ```
4. ```
   1211
   ```
5. ```
   111221
   ```

1 被读作 "one 1" ("一个一") , 即 11。 11 被读作 "two 1s" ("两个一"）, 即 21。 21 被读作 "one 2", "one 1" （"一个二" , "一个一") , 即 1211。

给定一个正整数 n（1 ≤ n ≤ 30），输出报数序列的第 n 项。

注意：整数顺序将表示为一个字符串。

```
示例 1:

输入: 1
输出: "1"
示例 2:

输入: 4
输出: "1211"
```

和斐波那契数列很像，可以采用同样的方法。

```
class Solution {
private:
    vector<string> say={"1","11","21","1211"};
public:
    string countAndSay(int n) {
        if(n<=say.size()) return  say[n-1];
        string tmp=countAndSay(n-1);
        string res;
        int k=1;
        for(int i=1;i<tmp.length();i++)
        {
            if(tmp[i]==tmp[i-1])
                k++;
            else
            {
                res+=to_string(k)+tmp[i-1];
                k=1;
            }
        }
        res+=to_string(k)+tmp[tmp.length()-1];
        say.push_back(res);
        return res;
        
    }
};
```

> 执行用时 : 12 ms, 在Count and Say的C++提交中击败了70.33% 的用户\
> 内存消耗 : 9.8 MB, 在Count and Say的C++提交中击败了20.77% 的用户


---

# Agent Instructions
This documentation is published with GitBook. GitBook is the documentation platform designed so that both humans and AI agents can read, navigate, and reason over technical content effectively. Learn more at gitbook.com.

## Querying This Documentation
If you need additional information that is not directly available in this page, you can query the documentation dynamically by asking a question.

Perform an HTTP GET request on the current page URL with the `ask` query parameter, and the optional `goal` query parameter:

```
GET https://dfine.gitbook.io/leetcode/38.count_and_say.md?ask=<question>&goal=<endgoal>
```

`ask` is the immediate question: it should be specific, self-contained, and written in natural language.
`goal` is optional and describes the broader end goal you are ultimately trying to accomplish on behalf of the user. GitBook uses it to tailor the answer towards what is most useful for that goal.

The response will contain a direct answer to the question and relevant excerpts and sources from the documentation.

Use this mechanism when the answer is not explicitly present in the current page, you need clarification or additional context, or you want to retrieve related documentation sections.
