题目描述:
提交:
class Solution: def getHappyString(self, n: int, k: int) -> str: strlist = [] def helper(n, s): if len(s) == n: strlist.append(s) return for c in ['a', 'b', 'c']: if len(s) > 0 and s[-1] != c: helper(n, s + c) elif not s: helper(n,s + c) helper(n,"") if k <= len(strlist): return strlist[k-1] else: return ""
优化:提前终止
class Solution: def getHappyString(self, n: int, k: int) -> str: cnt = 0 for i in range(3**n): s = "" for x in range(n): s = "abc"[i//3**x%3]+s flag = True for i in range(1, len(s)): if s[i] == s[i-1]: flag = False #print(s) if flag: #print(s) cnt += 1 if cnt == k: return s return ""