地址:https://leetcode-cn.com/problems/letter-case-permutation/

我写的题解地址:https://leetcode-cn.com/problems/letter-case-permutation/solution/shen-du-you-xian-bian-li-hui-su-suan-fa-python-dai/

思路:

1、这道题是直接修改方案,相当于回溯的过程,请重点理解这个过程;

2、类似问题还有「力扣」第 17 题:电话号码的字母组合题解

Java 代码:

import java.util.ArrayList;
import java.util.List;

public class Solution {

    public List<String> letterCasePermutation(String S) {
        int len = S.length();
        List<String> res = new ArrayList<>();
        if (len == 0) {
            return res;
        }
        char[] charArray = new char[len];
        dfs(S, 0, len, charArray, res);
        return res;
    }

    private void dfs(String S, int start, int len, char[] charArray, List<String> res) {
        if (start == len) {
            res.add(new String(charArray));
            return;
        }
        charArray[start] = S.charAt(start);
        dfs(S, start + 1, len, charArray, res);

        // 如果是字符,就可以派生出一个新分支
        if (Character.isLetter(S.charAt(start))) {
            charArray[start] = (char) (S.charAt(start) ^ (1 << 5));
            dfs(S, start + 1, len, charArray, res);
        }
    }

    public static void main(String[] args) {
        String S = "a1b2";
        Solution solution = new Solution();
        List<String> res = solution.letterCasePermutation(S);
        System.out.println(res);
    }
}

Python 代码:

from typing import List


class Solution:
    def letterCasePermutation(self, S: str) -> List[str]:
        size = len(S)
        if size == 0:
            return []

        res = []
        arr = list(S)
        self.__dfs(arr, size, 0, res)
        return res

    def __dfs(self, arr, size, start, res):
        if start == size:
            res.append(''.join(arr))
            return

        # 先把当前加到 pre 里面
        self.__dfs(arr, size, start + 1, res)

        # 如果是字母,就变换大小写
        if arr[start].isalpha():
            arr[start] = chr(ord(arr[start]) ^ (1 << 5))
            self.__dfs(arr, size, start + 1, res)