




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.
1using System;
2using System.Text;
3
4public class Solution {
5    public string CountAndSay(int n) {
6        string result = "1";
7        for (int i = 1; i < n; i++) {
8            StringBuilder temp = new StringBuilder();
9            int j = 0;
10            while (j < result.Length) {
11                char currentDigit = result[j];
12                int count = 0;
13                while (j < result.Length && result[j] == currentDigit) {
14                    j++;
15                    count++;
16                }
17                temp.Append(count).Append(currentDigit);
18            }
19            result = temp.ToString();
20        }
21        return result;
22    }
23
24    public static void Main() {
25        Solution sol = new Solution();
26        Console.WriteLine(sol.CountAndSay(4));
27    }
28}The C# version employs the StringBuilder class to build the result string for each step efficiently.
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.
1
This Java solution constructs the sequence by calling a nextSequence function on the result of the recursive call. Recursion simplifies managing the multiple sequence transformations.