Bootstrap

LeetCode 1415. 长度为 n 的开心字符串中字典序第 k 小的字符串

原题目:https://leetcode-cn.com/problems/the-k-th-lexicographical-string-of-all-happy-strings-of-length-n/

 

代码:

class Solution {
    vector<string> ans;
    vector<char> p {'a','b','c'};
    void dfs(int &n,string & tmp){
        if(tmp.size()==n){
            ans.push_back(tmp);return;
        }
        for(char& c:p){
            if(tmp.size() && c == tmp.back()) continue;
            tmp.push_back(c);
            dfs(n,tmp);
            tmp.pop_back();
        }
        
    }
public:
    string getHappyString(int n, int k) {
        string tmp;
        dfs(n,tmp);
        if(k>ans.size()) return"";
        return ans[k-1];
    }
};

 

 
;