问题链接:https://leetcode-cn.com/problems/letter-case-permutation/submissions/
思路
https://leetcode-cn.com/problems/letter-case-permutation/solution/shen-du-you-xian-bian-li-hui-su-suan-fa-python-dai/
效率
执行用时 :80 ms, 在所有 python3 提交中击败了61.95% 的用户
内存消耗 :14.3 MB, 在所有 python3 提交中击败了14.49%的用户
代码
class Solution:
def letterCasePermutation(self, S: str) -> List[str]:
size = len(S)
if size == 0:
return []
res = []
path = []
self.__dfs(S, size, 0, path, res)
return res
def __dfs(self, S, size, index, path, res):
if index == size:
return res.append(''.join(path))
path.append(S[index])
self.__dfs(S, size, index + 1, path, res)
path.pop()
# 如果是字母,就变换大小写
if S[index].isalpha():
path.append(chr(ord(S[index]) ^ (1 << 5)))
self.__dfs(S, size, index + 1, path, res)
path.pop()
大小写转换:
ord(‘a’) #将字符转化为十进制数 —>97
chr(97) #将十进制数转化为字符—>a
1<<5 #左移操作,2的幂相关—>25 *1=32 (if 2<< 5 —>25*2)
^ #异或 相同为0,相异为1
大小写转换具体流程:
1,32–(二进制数)–>0100000
2,a–(转换十进制数)–>97–(转换二进制数)–>1100001^0100000–>1000001-转换十进制数->65–(转字符)->A
3,A–(转换十进制数)–>65–(转换二进制数)–>1000001^0100000–>1100001-转换十进制数->97–(转字符)->a
感想
递归和回溯需要再理解和练习