給定一個字符串S
,通過將字符串S
中的每個字母轉變大小寫,我們可以獲得一個新的字符串。返回所有可能得到的字符串集合。
示例: 輸入: S = "a1b2" 輸出: ["a1b2", "a1B2", "A1b2", "A1B2"] 輸入: S = "3z4" 輸出: ["3z4", "3Z4"] 輸入: S = "12345" 輸出: ["12345"]
回溯:
static IList<IList<char>> res = new List<IList<char>>();
static void Main(string[] args)
{
List<string> res = new List<string>();
LetterCasePermutation("1s1s");
}
public static IList<string> LetterCasePermutation(string S)
{
List<string> res = new List<string>();
Helper(S.ToCharArray(), 0, res);
return res;
}
public static void Helper(char[] arr, int index, List<string> res)
{
if (index == arr.Length)
res.Add(new String(arr));
else
{
if (Char.IsDigit(arr[index]))
Helper(arr, index + 1, res);
else
{
arr[index] = Char.ToUpper(arr[index]);
Helper(arr, index + 1, res);
arr[index] = Char.ToLower(arr[index]);
Helper(arr, index + 1, res);
}
}
}
要理解回溯算法的結構。