784. Letter Case Permutation

问题:

给定一个由字母和数字组成的字符串。

任意字母可以变换大小写,以组成新的字符串。

求给定字符串能够组成字符串的所有可能。

Example 1:
Input: S = "a1b2"
Output: ["a1b2","a1B2","A1b2","A1B2"]

Example 2:
Input: S = "3z4"
Output: ["3z4","3Z4"]

Example 3:
Input: S = "12345"
Output: ["12345"]

Example 4:
Input: S = "0"
Output: ["0"]
 
Constraints:
S will be a string with length between 1 and 12.
S will consist only of letters or digits.

  

解法:Backtracking(回溯算法)

  • 状态:当前pos为止,构成的新字符串s[0~pos]
  • 选择:当前pos上的字符:
    • 数字:他自己
    • 字母:他自己+他的大小写转换
  • 递归退出条件:pos==字符串长度

 

代码参考:

 1 class Solution {
 2 public:
 3     void backtrack(vector<string>& res, string& path, int pos) {
 4         if(pos==path.length()) {
 5             res.push_back(path);
 6             return;
 7         }
 8         backtrack(res, path, pos+1);
 9         int diff = 'A'-'a';
10         if(path[pos]>='a' && path[pos]<='z') {
11             path[pos]+=diff;
12             backtrack(res, path, pos+1);
13             path[pos]-=diff;
14         } else if(path[pos]>='A' && path[pos]<='Z') {
15             path[pos]-=diff;
16             backtrack(res, path, pos+1);
17             path[pos]+=diff;
18         }
19         return;
20     }
21     vector<string> letterCasePermutation(string S) {
22         vector<string> res;
23         backtrack(res, S, 0);
24         return res;
25     }
26 };

 

posted @ 2021-01-27 14:14  habibah_chang  阅读(96)  评论(0编辑  收藏  举报