Letter Case Permutation(784)
阿新 • • 發佈:2018-12-24
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: 字串長度, l: 字元數量. 最好的情況;全都是數字;最壞的情況:全都是字母.)
Space complexity : O( ) + O( )stack.
思路:
- DFS思想
- 如下圖: