c# leetcode 784. 字母大小寫全排列(回溯算法)

 給定一個字符串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);
                }
            }
        }

要理解回溯算法的結構。

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章