784. Letter Case Permutation

问题描述:

Given a string S, we can transform every letter individually to be lowercase or uppercase to create another string.  Return a list of all possible strings we could create.

Examples:
Input: S = "a1b2"
Output: ["a1b2", "a1B2", "A1b2", "A1B2"]

Input: S = "3z4"
Output: ["3z4", "3Z4"]

Input: S = "12345"
Output: ["12345"]

Note:

  • S will be a string with length at most 12.
  • S will consist only of letters or digits.

解题思路:

看到这个列举所有可能,首先想到的是dfs。

但是这里有两种状态:大写和小写;所以我们可以现将其全部转换为小写,然后用dfs进行翻转。

 

需要注意的是:

1. dfs一定会改变某一个字母,所以全部都是小写的字母需要自己加入。

2. dfs时翻转后加入返回数组,并且递归dfs,但是之后要将改动的数字变回来。

所以递归第一层就是:只有一个大写字母的所有可能,第二层:两个… 诸如此类。

 

 

代码:

class Solution {
public:
    vector<string> letterCasePermutation(string S) {
        vector<string> ret;
        for(int i = 0; i < S.size(); i++){
            if(!isdigit(S[i]) && isupper(S[i])) S[i] = tolower(S[i]);
        }
        cout<<S<<endl;
        ret.push_back(S);
        dfs(ret, 0, S);
        return ret;
    }
    void dfs(vector<string> &ret, int start, string s){
        for(int i = start; i < s.size(); i++){
            if(isdigit(s[i])) continue;
            s[i] = toupper(s[i]);
            ret.push_back(s);
            dfs(ret, i+1, s);
            s[i] = tolower(s[i]);
        }
    }
};

 

posted @ 2018-07-13 06:30  妖域大都督  阅读(119)  评论(0编辑  收藏  举报