




Sponsored
This approach involves constructing the sequence iteratively. We start from the base case, which is '1', and iteratively build up the strings by counting and saying the digits from the last constructed string.
Time Complexity: O(2^n) as the length of the string grows exponentially.
Space Complexity: O(2^n) for storing the string.
1#include <stdio.h>
2#include <stdlib.h>
3#include <string.h>
4
5char* countAndSay(int n) {
6    char* result = malloc(2);
7    strcpy(result, "1");
8    for (int i = 1; i < n; i++) {
9        int len = strlen(result);
10        char* temp = malloc(2 * len + 1);
11        int index = 0;
12        for (int j = 0; j < len;) {
13            char current_digit = result[j];
14            int count = 0;
15            while (j < len && result[j] == current_digit) {
16                count++;
17                j++;
18            }
19            index += sprintf(temp + index, "%d%c", count, current_digit);
20        }
21        free(result);
22        result = temp;
23    }
24    return result;
25}
26
27int main() {
28    int n = 4;
29    char* result = countAndSay(n);
30    printf("%s\n", result);
31    free(result);
32    return 0;
33}The solution initializes the result to '1'. For each iteration, it constructs the next sequence by reading the current result, counting contiguous digits, and forming a new string based on these counts. Memory is managed dynamically to accommodate changing string sizes.
The recursive approach defines the function countAndSay recursively by computing countAndSay(n-1), then generating the count-and-say encoding for it.
This method involves less memory usage on the function stack compared to an iterative approach but still leverages recursion for elegance.
Time Complexity: O(2^n) as strings grow exponentially.
Space Complexity: O(2^n) due to storing strings and O(n) recursion stack.
1using System;
2using System.Text;
public class Solution {
    private string NextSequence(string seq) {
        StringBuilder result = new StringBuilder();
        for (int i = 0; i < seq.Length;) {
            char currentChar = seq[i];
            int count = 0;
            while (i < seq.Length && seq[i] == currentChar) {
                i++;
                count++;
            }
            result.Append(count).Append(currentChar);
        }
        return result.ToString();
    }
    public string CountAndSay(int n) {
        if (n == 1) return "1";
        string prevResult = CountAndSay(n - 1);
        return NextSequence(prevResult);
    }
    public static void Main() {
        Solution sol = new Solution();
        Console.WriteLine(sol.CountAndSay(4));
    }
}C# implementation makes use of recursion to compute sequences with NextSequence extending every string based on counting each digit from previous results.