The k-th Lexicographical String of All Happy Strings of Length n
定义一个happy string, 求第k个字典序的happy string是什么.
暴力解, 好像没有什么简化方法.
class Solution {
public String getHappyString(int n, int k) {
List<String> list = new ArrayList<>();
dfs(n, list, "", new char[]{'a', 'b', 'c'});
if(k < 0 || k > list.size())
return "";
else
return list.get(k - 1);
}
public void dfs(int n, List<String> list, String s, char[] c) {
if(n == s.length()){
list.add(s);
return;
}
for(char cc : c) {
if(s.isEmpty())
dfs(n, list, s+cc,c);
else
{
if(s.charAt(s.length() - 1) != cc)
dfs(n, list, s+cc, c);
}
}
}
}