20221030 - 784. Letter Case Permutation 字母大小写全排列(回溯)

190 阅读1分钟

Given a string s, you can transform every letter individually to be lowercase or uppercase to create another string.

Return a list of all possible strings we could create. Return the output in any order.

Example 1

Input: s = "a1b2"
Output: ["a1b2","a1B2","A1b2","A1B2"]

Example 2

Input: s = "3z4"
Output: ["3z4","3Z4"]

Constraints

  • 1 <= s.length <= 12
  • s consists of lowercase English letters, uppercase English letters, and digits.

Solution

异或运算可以看作半加运算(不进位的加法)

class Solution {
public:
    void dfs(string &s, int pos, vector<string> &res) {
        while (pos < s.size() && isdigit(s[pos])) {
            pos++;
        }
        if (pos == s.size()) {
            res.emplace_back(s);
            return;
        }
        s[pos] ^= 32;
        dfs(s, pos + 1, res);
        s[pos] ^= 32;
        dfs(s, pos + 1, res);
    }
    vector<string> letterCasePermutation(string s) {
        vector<string> ans;
        dfs(s, 0, ans);
        return ans;
    }
};

题目链接:784. 字母大小写全排列 - 力扣(LeetCode)