consists only of letters of the set ['a', 'b', 'c'].
s[i] != s[i + 1] for all values of i from 1 to s.length - 1 (string is 1-indexed).
For example, strings "abc", "ac", "b" and "abcbabcbcb" are all happy strings and strings "aa", "baa" and "ababbc" are not happy strings.
Given two integers n and k, consider a list of all happy strings of length n sorted in lexicographical order.
Return the kth string of this list or return an empty string if there are less than k happy strings of length n.
Example 1:
Input: n = 1, k = 3
Output: "c"
Explanation: The list ["a", "b", "c"] contains all happy strings of length 1. The third string is "c".
Example 2:
Input: n = 1, k = 4
Output: ""
Explanation: There are only 3 happy strings of length 1.
Example 3:
Input: n = 3, k = 9
Output: "cab"
Explanation: There are 12 different happy string of length 3 ["aba", "abc", "aca", "acb", "bab", "bac", "bca", "bcb", "cab", "cac", "cba", "cbc"]. You will find the 9th string = "cab"
Constraints:
1 <= n <= 10
1 <= k <= 100
Solutions
Solution 1: DFS
We use a string \(\textit{s}\) to record the current string, initially an empty string. Then, we design a function \(\text{dfs}\) to generate all happy strings of length \(n\).
The implementation of the function \(\text{dfs}\) is as follows:
If the length of the current string is equal to \(n\), add the current string to the answer array \(\textit{ans}\) and return;
If the length of the answer array is greater than or equal to \(k\), return directly;
Otherwise, we iterate over the character set \(\{a, b, c\}\). For each character \(c\), if the current string is empty or the last character of the current string is not equal to \(c\), add the character \(c\) to the current string, then recursively call \(\text{dfs}\). After the recursion ends, remove the last character of the current string.
Finally, we check if the length of the answer array is less than \(k\). If it is, return an empty string; otherwise, return the \(k\)-th element of the answer array.
The time complexity is \(O(n \times 2^n)\), and the space complexity is \(O(n)\). Here, \(n\) is the length of the string.