LeetCode 784. 字母大小写全排列

784. 字母大小写全排列

 

【回溯法】

class Solution {

    // 回溯 4:30 6

    int n;
    StringBuilder sb = new StringBuilder();
    List ans = new ArrayList();

    void backTrack(int t) {
        if (t == n) {
            ans.add(sb.toString()); return;
        }
        char c = sb.charAt(t);
        if (c >= '0' && c <= '9') backTrack(t + 1);
        else {
            backTrack(t + 1);
            if (c >= 'a' && c <= 'z') {
                sb.setCharAt(t, (char)(c + 'A' - 'a'));
                backTrack(t + 1);
                sb.setCharAt(t, c);
            } else {
                sb.setCharAt(t, (char)(c + 'a' - 'A'));
                backTrack(t + 1);
                sb.setCharAt(t, c);
            }
        }
    }

    public List letterCasePermutation(String s) {
        this.n = s.length();
        sb.append(s);
        backTrack(0);
        return ans;
    }
}

【小技巧】大小写转换可以通过异或32来实现

class Solution {

    // 回溯法 8:18 ^32

    List ans = new ArrayList();
    int n;
    StringBuilder sb = new StringBuilder();

    void backTrack(int t) {
        if (t == n) {
            ans.add(sb.toString()); return;
        }
        backTrack(t + 1);
        char c = sb.charAt(t);
        if (c < '0' || c > '9') {
            sb.setCharAt(t, (char)(c ^ 32));
            backTrack(t + 1);
            sb.setCharAt(t, (char)c);
        }
    }

    public List letterCasePermutation(String s) {
        this.n = s.length();
        sb.append(s);
        backTrack(0);
        return ans;
    }
}

 

 

你可能感兴趣的:(LeetCode,leetcode,回溯法,位运算)