https://leetcode-cn.com/problems/letter-case-permutation/
Given a string S, S by the string shift each letter case, we can get a new string. Returns the set of all possible strings obtained.
Example:
Input: S = "a1b2"
Output: [ "a1b2", "a1B2 ", "A1b2", "A1B2"]
Input: S = "3z4"
Output: [ "3z4", "3Z4 "]
Input: S = "12345"
Output: [ "12345"]
Note:
Length S no more than 12.
S only by numbers and letters.
Chicken dishes to try:
The first feeling is back. I started out to write, but can not think of a recursive end condition of emmm
Worship Gangster Code:
[Recursive backtracking]
With vector <string> res store the results, s string to be processed
Recursion End Condition:
when S is an empty string, the end of the recursion, write result
recursive equatorial three cases:
Encountered a number, add this number on the letter continues recursively
encountered lowercase letters, lowercase letters on the letter added this continues recursively + Add this capital letters on the letter continues recursively
encountered in uppercase letters, add the capital letters on the letter recursively + Add to this the letter lowercase letters recursively
1 class Solution { 2 public: 3 vector<string> res; 4 vector<string> letterCasePermutation(string S) { 5 letterCase("", S); 6 return res; 7 } 8 void letterCase(string letter, string S) { 9 if (S.size()==0) { 10 res.push_back(letter); 11 return; 12 } 13 char s = S[0]; 14 letterCase(letter+s, S.substr(1)); 15 if (s >= 'a' && s <='z') { 16 letterCase(letter + char(toupper(s)), S.substr(1)); 17 } else if (s >= 'A' && s <='Z') { 18 letterCase(letter + char(tolower(s)), S.substr(1)); 19 } 20 } 21 };
Taurus [O (n)]
. 1 class Solution { 2 public : . 3 Vector < String > letterCasePermutation ( String S) { . 4 int size = s.size (); . 5 Vector < String > V; . 6 // initialization . 7 int NUM = . 1 ; . 8 v.push_back ( "" ); . 9 for ( int I = 0 ; I <size; I ++) { // individually determined for each character string 10 IF (the isalpha (S [I])) {// character . 11 for ( int J = 0 ; J <NUM; J ++ ) { 12 is String temp1 = V [J]; 13 is String temp2 of = temp1; 14 temp1 + = S [I]; 15 V [J] = temp1 ; 16 S [I] ^ = 32 ; // clever use of the XOR operation, the conversion to complete the case . 17 temp2 of + = S [I]; 18 is v.push_back (temp2 of); . 19 } 20 is NUM = NUM *2; 21 } else { // 是数字 22 for (int j = 0; j < num; j ++) { 23 string temp = v[j]; 24 temp += S[i]; 25 v[j] = temp; 26 } 27 } 28 } 29 return v; 30 } 31 };
Source: stay button (LeetCode)
link: https: //leetcode-cn.com/problems/letter-case-permutation
copyrighted by deduction from all networks. Commercial reprint please contact the authorized official, non-commercial reprint please indicate the source.