784. Letter Case Permutation

784. Letter Case Permutation

一、題目

Given a string s, you can transform every letter individually to be lowercase or uppercase to create another string.

Return a list of all possible strings we could create. Return the output in any order.

 

Example 1:

Input: s = "a1b2" Output: ["a1b2","a1B2","A1b2","A1B2"]

Example 2:

Input: s = "3z4" Output: ["3z4","3Z4"]

 

Constraints:

  • 1 <= s.length <= 12
  • s consists of lowercase English letters, uppercase English letters, and digits.

 

二、程式作法

public class Solution
{
    public IList<string> res = new List<string>();
    public List<int> addr = new List<int>();
    char[] chars = Array.Empty<char>();

    public IList<string> LetterCasePermutation(string s)
    {
        chars = s.ToCharArray();
        for (int i = 0; i < chars.Length; i++)
            if (char.IsLetter(chars[i]))
                addr.Add(i);

        Helper(0);

        return res;
    }

    public void Helper(int ind)
    {
        if (ind == addr.Count)
            res.Add(new string(chars));
        else
        {
            Helper(ind + 1);
            if (char.IsUpper(chars[addr[ind]]))
                chars[addr[ind]] = char.ToLower(chars[addr[ind]]);
            else
                chars[addr[ind]] = char.ToUpper(chars[addr[ind]]);
            Helper(ind + 1);
        }
    }
}

 

三、思路筆記

目的為將字串裡所有的英文字母做大小寫排列。

我們可知道相同的排列順序,每一次變換一字母的大小寫法都是一種組合,

例如如果有 2 個英文字母則組合為 2^2=4 種組合;3 個英文字母則組合為 2^3=8 種組合。