程式語言 - LeetCode - C++ - 1415. The k-th Lexicographical String of All Happy Strings of Length n



參考資訊:
https://algo.monster/liteproblems/1415

題目:


解答:

class Solution {
public:
    string getHappyString(int n, int k) {
        string tmp;
        vector<string> out;

        auto gen = [&](this auto&& gen) -> int {
            if (tmp.size() >= n) {
                out.emplace_back(tmp);
                return 1;
            }

            for (char ch = 'a'; ch <= 'c'; ++ch) {
                if (tmp.empty() || tmp.back() != ch) {
                    tmp.push_back(ch);
                    gen();
                    tmp.pop_back();
                }
            }
            return 0;
        };

        gen();
        return out.size() < k ? "" : out[k - 1];
    }
};