Bootstrap

穷举vs暴搜vs深搜vs回溯vs剪枝系列一>字母大小写全排列

题目: 

 


解析: 

 


代码: 

private List<String> ret;
    private StringBuffer path;
    public List<String> letterCasePermutation(String s) {
        ret = new ArrayList<>();
        path = new StringBuffer();
        dfs(s,0);
        return ret;
    }

    private void dfs(String s, int pos){
        
        if(pos == s.length()){
            ret.add(path.toString());
            return;
        } 

        char ch = s.charAt(pos);

        //改变
        if(ch < '0' || ch > '9'){
            char tmp = change(ch);
            path.append(tmp);
            dfs(s,pos+1);
            path.deleteCharAt(path.length()-1);//恢复现场
        }

        //不变
        path.append(ch);
        dfs(s,pos+1);
        path.deleteCharAt(path.length()-1);//恢复现场
    }  

    private char change(char ch){
        if(ch >= 'a' && ch <= 'z') return ch -= 32;//小写转大写
        else return ch += 32;//大写转小写
    }
;