Letter Case Permutation(784)

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”]

C++代码:

class Solution
{
public:
  vector<string> letterCasePermutation(string S) {
    vector<string> ans;
    DFS(ans , S , 0);
    return ans;
  }
private:
  void DFS(vector <string> &ans, string &S,int i){
    if(i == S.length()) {
      ans.push_back(S);
      return ;
    }
    DFS(ans,S,i+1);
    if(isalpha(S[i])){
      S[i] ^= (1<<5);  //a->A,A->a
      DFS(ans,S,i+1);
      S[i] ^=(1<<5); //这里可要可不要,不需要回溯, 不恢复状态也没有关系
    } else{
      return;
    }
  }
};

Complexity Analysis:

Time complexity : O( n 2 l n*2^{l} ). ( n: 字符串长度, l: 字符数量. 最好的情况;全都是数字;最坏的情况:全都是字母.)
Space complexity : O( n n ) + O( n 2 l n*2^{l} )stack.

思路:

  • DFS思想
  • 如下图:

Leetcode784

猜你喜欢

转载自blog.csdn.net/kelly_fumiao/article/details/85116191
今日推荐