784. 字母大小写全排列

image.png

image.png

1、路径:也就是已经做出的选择。
2、选择列表:也就是你当前可以做的选择。
3、结束条件:也就是到达决策树底层,无法再做选择的条件。

  1. result = []
  2. def backtrack(路径, 选择列表):
  3. if 满足结束条件:
  4. result.add(路径)
  5. return
  6. for 选择 in 选择列表:
  7. 做选择
  8. backtrack(路径, 选择列表)
  9. 撤销选择

回溯算法

  1. package main
  2. import (
  3. "fmt"
  4. "strings"
  5. "unicode"
  6. )
  7. func main() {
  8. fmt.Println(letterCasePermutation("a1b2"))
  9. }
  10. func letterCasePermutation(S string) []string {
  11. res :=make([]string,0)
  12. dfs([]byte(S),0,&res)
  13. return res
  14. }
  15. func dfs(char []byte,index int,res *[]string){
  16. if index==len(char) {
  17. *res = append(*res,string(char))
  18. return
  19. }
  20. dfs(char,index+1,res)
  21. if unicode.IsLetter(rune(char[index])) {
  22. if unicode.IsLower(rune(char[index])) {
  23. char[index] = strings.ToUpper(string(char[index]))[0]
  24. }else {
  25. char[index] = strings.ToLower(string(char[index]))[0]
  26. }
  27. dfs(char,index+1,res)
  28. }
  29. }

image.png

char[index] = char[index]^1<<5 异或32处理

  1. func dfs(char []byte,index int,res *[]string){
  2. if index==len(char) {
  3. *res = append(*res,string(char))
  4. return
  5. }
  6. dfs(char,index+1,res)
  7. if unicode.IsLetter(rune(char[index])) {
  8. char[index] = char[index]^1<<5
  9. dfs(char,index+1,res)
  10. }
  11. }
  1. class Solution {
  2. List<String> ans = new ArrayList<>();
  3. int dis = 'A'-'a';
  4. public List<String> letterCasePermutation(String S) {
  5. char[] str = S.toCharArray();
  6. dfs(str,0);
  7. return ans;
  8. }
  9. /**
  10. * 深度优先搜索
  11. * str 字符数组
  12. * index 当前搜索深度
  13. **/
  14. private void dfs(char[] str,int index){
  15. if(index==str.length){
  16. ans.add(new String(str));
  17. return;
  18. }
  19. if(str[index]>='a'&&str[index]<='z'){//该位置为小写字母
  20. dfs(str,index+1); //往下一深度搜索
  21. str[index]+=dis; //字母大写
  22. dfs(str,index+1); //往下一深度搜索
  23. str[index]-=dis; //字母变回小写
  24. }else if(str[index]>='A'&&str[index]<='Z'){
  25. dfs(str,index+1);
  26. str[index]-=dis;
  27. dfs(str,index+1);
  28. str[index]+=dis;
  29. }else{
  30. dfs(str,index+1);
  31. }
  32. return;
  33. }
  34. }