Small knowledge, big challenge! This article is participating in the creation activity of “Essential Tips for Programmers”.

The title

Given a positive integer n, prints the NTH term of the appearance sequence.

An “appearance sequence” is a sequence of integers, starting with the number 1, and each item in the sequence is a description of the previous item.

You can think of it as a sequence of numeric strings defined by a recursive formula:

  • countAndSay(1) = "1"
  • countAndSay(n)Is thecountAndSay(n-1)Is then converted to another numeric string.

The first five are as follows:

1. 1, 2. 11, 3. 21, 4. 1211, 5. 111221 The first term is the number 1 that describes the previous term, and this number is 1, “one 1”, which is called “11”, which describes the previous term, and this number is 11, which is called “21”, which describes the previous term, So this number right here is 21 which is “one 2 + one 1”, let’s call it “1211” to describe the previous term, this number right here is 1211 which is” one 1 + one 2 + two 1s “, let’s call it “111221”.

To describe a numeric string, you first split the string into a minimum number of groups, each consisting of at most consecutive identical characters. Then for each group, the number of characters is described first, and then the characters are described, forming a description group. To convert the description to a numeric string, replace the number of characters in each group with a number, and then concatenate all the description groups.

For example, the numeric string “3322251” is described as follows:

 

Example 1:

Input: n = 1 Output: “1” Explanation: This is a basic example.

Example 2:

Input: n = 4 Output: “1211” CountAndSay (1) = “1” countAndSay(2) = read “1” = one 1 = “11” countAndSay(3) = read “11” = two 1 = “21” countAndSay(4) = read “21” = 12 + 11 = “12” + “11” = “1211”

 

Tip:

  • 1 <= n <= 30

Their thinking

Conventional thinking

/ * * *@param {number} n
 * @return {string}* /
var countAndSay = function(n) {
    let result = '1'
    if(n === 1) return '1'
    for(let i = 2; i <=n ; i++) {
        let aes = ' '
        let total = 0
        for(let t = 0; t < result.length; t++) {
            const a = result[t]
            total = t === 0 ? 1 : result[t] === result[t - 1]? total +1 : 1
            if(result[t] ! == result[t +1]) {
                aes = aes + total + a
            }
        }
        result = aes
    }
    return result
};
Copy the code

regular

var countAndSay = function(n) {
    return n==1? '1' : countAndSay(n-1).replace(/(\d)\1*/g.item= >`${item.length}${item[0]}`)};Copy the code

The last

I dreamed of traveling with swords

Look at the prosperity of the world

Young heart always some frivolous

Just a man after all

No regrets I go my way