[LeetCode] 1079. Letter Tile Possibilities
Posted CNoodle
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了[LeetCode] 1079. Letter Tile Possibilities相关的知识,希望对你有一定的参考价值。
You have n
tiles
, where each tile has one letter tiles[i]
printed on it.
Return the number of possible non-empty sequences of letters you can make using the letters printed on those tiles
.
Example 1:
Input: tiles = "AAB" Output: 8 Explanation: The possible sequences are "A", "B", "AA", "AB", "BA", "AAB", "ABA", "BAA".
Example 2:
Input: tiles = "AAABBC" Output: 188
Example 3:
Input: tiles = "V" Output: 1
Constraints:
1 <= tiles.length <= 7
tiles
consists of uppercase English letters.
活字印刷。
你有一套活字字模 tiles,其中每个字模上都刻有一个字母 tiles[i]。返回你可以印出的非空字母序列的数目。
注意:本题中,每个活字字模只能使用一次。
来源:力扣(LeetCode)
链接:https://leetcode.cn/problems/letter-tile-possibilities
著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。
思路是 DFS backtracking。这道题有点类似求子集那一类的题。因为 input 中有可能有重复字母,为了不重复使用,我们需要将 input 字符串中的字母进行排序,再通过一个额外的 visited 数组判断某个字母是否有被重复使用。
时间O(nlogn)
空间O(n)
Java实现
class Solution int count; public int numTilePossibilities(String tiles) count = 0; char[] letters = tiles.toCharArray(); Arrays.sort(letters); boolean[] visited = new boolean[letters.length]; dfs(letters, 0, visited); return count; private void dfs(char[] letters, int index, boolean[] visited) if (index == letters.length) return; for (int i = 0; i < letters.length; i++) if (visited[i]) continue; if (i - 1 >= 0 && letters[i] == letters[i - 1] && !visited[i - 1]) continue; count++; visited[i] = true; dfs(letters, index + 1, visited); visited[i] = false;
LeetCode(17)Letter Combinations of a Phone Number
题目如下:
Python代码:
class Solution(object): def letterCombinations(self, digits): """ :type digits: str :rtype: List[str] """ if not digits: return [] dic = {\'2\':\'abc\',\'3\':\'def\',\'4\':\'ghi\',\'5\':\'jkl\',\'6\':\'mno\',\'7\':\'pqrs\',\'8\':\'tuv\',\'9\':\'wxyz\'} result = [] self.helper(digits,dic,0,"",result) return result def helper(self,digits,dic,index,temp,result): if index==len(digits): result.append(temp) else: s = dic[digits[index]] for i in s: temp += i self.helper(digits,dic,index+1,temp,result) temp = temp[:-1]
以上是关于[LeetCode] 1079. Letter Tile Possibilities的主要内容,如果未能解决你的问题,请参考以下文章
[LeetCode] 1079. Letter Tile Possibilities
LeetCode(17)Letter Combinations of a Phone Number
LeetCode题828 —— Unique Letter String