码迷,mamicode.com
首页 > 其他好文 > 详细

leetcode1081

时间:2019-06-09 22:30:02      阅读:149      评论:0      收藏:0      [点我收藏+]

标签:self   simple   tps   ret   and   回溯   false   rac   count   

 1 class Solution(object):
 2     def __init__(self):
 3         self.count = 0
 4     
 5     def dfs(self, tiles, used, visited, path):
 6         
 7         if len(path) > 0 and path not in visited:
 8             visited.add(path)
 9             self.count += 1
10 
11         for i in range(len(tiles)):
12             if used[i]:
13                 continue
14             used[i] = True                            
15             self.dfs(tiles, used, visited, path + tiles[i])        
16             used[i] = False
17                 
18 
19     def numTilePossibilities(self, tiles):
20         """
21         :type tiles: str
22         :rtype: int
23         """
24 
25         visited = set()
26         used = [False] * len(tiles)        
27         self.dfs(tiles, used, visited, "")            
28         return self.count

回溯法,参考:https://leetcode.com/problems/letter-tile-possibilities/discuss/308486/Simple-python-solution-with-backtracking

 

另外一行样式:

1 class Solution:
2     def numTilePossibilities(self, tiles: str) -> int:
3         return sum(len(set(itertools.permutations(tiles, i))) for i in range(1, len(tiles) + 1))

参考:https://leetcode.com/problems/letter-tile-possibilities/discuss/308518/Python-1-liner

leetcode1081

标签:self   simple   tps   ret   and   回溯   false   rac   count   

原文地址:https://www.cnblogs.com/asenyang/p/10995058.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!