forked from everthis/leetcode-js
-
Notifications
You must be signed in to change notification settings - Fork 0
/
1079-letter-tile-possibilities.js
74 lines (67 loc) · 1.47 KB
/
1079-letter-tile-possibilities.js
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
/**
* @param {string} tiles
* @return {number}
*/
const numTilePossibilities = function(tiles) {
const obj = { count: 0 };
dfs(tiles, new Array(tiles.length).fill(false), new Set(), "", obj);
return obj.count;
};
function dfs(tiles, used, visited, path, obj) {
if (path !== "" && !visited.has(path)) obj.count++;
visited.add(path)
for (let i = 0; i < tiles.length; i++) {
if (used[i]) continue;
used[i] = true;
dfs(tiles, used, visited, path + tiles.charAt(i), obj);
used[i] = false;
}
}
// another
/**
* @param {string} tiles
* @return {number}
*/
const numTilePossibilities = function(tiles) {
let used = new Array(tiles.length).fill(false);
let visited = new Set();
let cnt = 0;
const dfs = (path) => {
if (path.length && !visited.has(path)) {
visited.add(path);
cnt++;
}
for (let i = 0; i < tiles.length; i++) {
if (used[i]) continue;
used[i] = true;
dfs(path + tiles[i]);
used[i] = false;
}
}
dfs('');
return cnt;
};
// another
/**
* @param {string} tiles
* @return {number}
*/
const numTilePossibilities = function(tiles) {
const count = new Array(26).fill(0)
const ACode = 'A'.charCodeAt(0)
for (let i = 0, len = tiles.length; i < len; i++) {
count[tiles.charCodeAt(i) - ACode]++
}
return dfs(count)
}
function dfs(arr) {
let sum = 0
for (let i = 0; i < 26; i++) {
if (arr[i] === 0) continue
sum++
arr[i]--
sum += dfs(arr)
arr[i]++
}
return sum
}