-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy path1079.letter-tile-possibilities.java
76 lines (70 loc) · 1.49 KB
/
1079.letter-tile-possibilities.java
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
/*
* @lc app=leetcode id=1079 lang=java
*
* [1079] Letter Tile Possibilities
*
* https://leetcode.com/problems/letter-tile-possibilities/description/
*
* algorithms
* Medium (74.96%)
* Likes: 525
* Dislikes: 22
* Total Accepted: 24.9K
* Total Submissions: 33.1K
* Testcase Example: '"AAB"'
*
* You have a set of 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.
*
*
*
* Example 1:
*
*
* Input: "AAB"
* Output: 8
* Explanation: The possible sequences are "A", "B", "AA", "AB", "BA", "AAB",
* "ABA", "BAA".
*
*
*
* Example 2:
*
*
* Input: "AAABBC"
* Output: 188
*
*
*
*
*
* Note:
*
*
* 1 <= tiles.length <= 7
* tiles consists of uppercase English letters.
*
*/
// @lc code=start
class Solution {
int total = 0;
public int numTilePossibilities(String tiles) {
Set<Integer> visited = new HashSet<>();
char[] cs = tiles.toCharArray();
Arrays.sort(cs);
dfs(cs, visited);
return total;
}
private void dfs(char[] tiles, Set<Integer> visited) {
for (int i = 0; i < tiles.length; i++) {
if (visited.contains(i)) continue;
if (i > 0 && tiles[i] == tiles[i - 1] && !visited.contains(i-1)) continue;
total++;
visited.add(i);
dfs(tiles, visited);
visited.remove(i);
}
}
}
// @lc code=end