LeetCode 784. Letter Case Permutation

原题链接在这里:https://leetcode.com/problems/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"]

Note:

  • S will be a string with length between 1 and 12.
  • S will consist only of letters or digits.

题解:

For each dfs level, state needs current index and current item.

When the index hits the end, add to res.

Time Complexity: O(exponential).

Space: O(S.lengt()).

AC Java:

 1 class Solution {
 2     public List<String> letterCasePermutation(String S) {
 3         List<String> res = new ArrayList<>();
 4         caseDfs(S, 0, new StringBuilder(), res);
 5         return res;
 6     }
 7     
 8     private void caseDfs(String s, int cur, StringBuilder sb, List<String> res){
 9         if(cur == s.length()){
10             res.add(sb.toString());
11             return;
12         }
13         
14         char c = s.charAt(cur);
15         if(Character.isDigit(c)){
16             sb.append(c);
17             caseDfs(s, cur+1, sb, res);
18             sb.deleteCharAt(sb.length()-1);
19         }else{
20             sb.append(Character.toLowerCase(c));
21             caseDfs(s, cur+1, sb, res);
22             sb.deleteCharAt(sb.length()-1);
23             
24             sb.append(Character.toUpperCase(c));
25             caseDfs(s, cur+1, sb, res);
26             sb.deleteCharAt(sb.length()-1);
27         }
28     }
29 }

AC Python:

 1 class Solution:
 2     def letterCasePermutation(self, S: str) -> List[str]:
 3         res = []
 4         self.dfs(S, 0, "", res)
 5         return res
 6     
 7     def dfs(self, S: str, cur: int, item: str, res: List[str]) -> None:
 8         if cur == len(S):
 9             res.append(item)
10             return
11         
12         if S[cur].isalpha():
13             self.dfs(S, cur + 1, item + S[cur].lower(), res)
14             self.dfs(S, cur + 1, item + S[cur].upper(), res)
15             
16         else:
17             self.dfs(S, cur + 1, item + S[cur], res)

类似Combinations.

posted @ 2019-09-12 11:18  Dylan_Java_NYC  阅读(258)  评论(0编辑  收藏  举报