zoukankan      html  css  js  c++  java
  • Leetcode784.字母大小写全排列

    题意

    给定一个字符串S,通过将字符串S中的每个字母转变大小写,我们可以获得一个新的字符串。返回所有可能得到的字符串集合。

    思路

    • 对于回溯题目画出它的递归树是最好分析的。可以看出1⃣️如果是数字,直接将数字加到当前保存结果的字符串str里,2⃣️如果是字母,那么要扩展2个结点,分别是它的大写字母和小写字母。这样最后递归到叶子结点就得到了一个解。递归树如下图所示

    代码

    class Solution {
    public:
        vector<string> ans;
    		//index为str字符串的长度
        void backtrace(string& str, string& S, int index)
        {
            if(index == S.size())
            {
                ans.push_back(str);
                return;
            }
            if(isdigit(S[index]))
            {
                str.push_back(S[index]);
                backtrace(str, S, index + 1);
                str.pop_back();
            }
            if(isalpha(S[index]))
            {
                //分别扩展小写字母,大写字母
                str.push_back(tolower(S[index]));
                backtrace(str, S, index + 1);
                str.pop_back();
    
                str.push_back(toupper(S[index]));
                backtrace(str, S, index + 1);
                str.pop_back();
            }
        }
        vector<string> letterCasePermutation(string S) {
            if(S.size() == 0)   return {};
            string path = "";
            backtrace(path, S, 0);
            return ans;
        }
    };
    
    如有转载,请注明出处QAQ
  • 相关阅读:
    bzoj1066: [SCOI2007]蜥蜴
    bzoj3504: [Cqoi2014]危桥
    bzoj2756: [SCOI2012]奇怪的游戏
    bzoj1570: [JSOI2008]Blue Mary的旅行
    Ultra-QuickSort
    Bin Packing
    Watering Grass
    区间覆盖
    抄书 Copying Books UVa 714
    分馅饼 Pie
  • 原文地址:https://www.cnblogs.com/MartinLwx/p/13598031.html
Copyright © 2011-2022 走看看