Leetcode第784题:字母大小写的全排列(Letters case permutation)

解题思路

使用回溯法。从左往右依次遍历字符,当遍历到字符串s的第i个字符c时:

  • 如果c为一个数字,继续检测下一个字符。
  • 如果c为一个字母,将其进行大小写转换,然后往后继续遍历;完成改写形式的子状态遍历后,将c进行恢复,继续往后遍历。
  • 完成当前字符串的遍历后,表示当前的子状态已经遍历完,该序列称为全排列中的一个。

大小写转换时可以用\(c+32\)来进行转换和恢复。

核心代码如下:

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;
    }
};
posted @ 2022-10-30 18:50  hql5  阅读(41)  评论(0)    收藏  举报