Leetcode 1079. Movable type printing
topic
你有一套活字字模 tiles,其中每个字模上都刻有一个字母 tiles[i]。返回你可以印出的非空字母序列的数目。
注意:本题中,每个活字字模只能使用一次。
Example 1:
输入:"AAB"
输出:8
解释:可能的序列为 "A", "B", "AA", "AB", "BA", "AAB", "ABA", "BAA"。
Example 2:
输入:"AAABBC"
输出:188
Ideas
- Since the size of tiles is very small, you can consider using recursion to solve the problem
- First write a recursive processing subset problem-only consider the increase of one character at a time, use find to remove duplication
- After getting the subset, use full permutation, and use map to remove duplicates. Finally, -1 is to remove the empty set
Code
class Solution {
public:
void dfs(vector<string>& res, string& tiles, string temp, int start) {
if (find(res.begin(), res.end(), temp) == res.end()) {
res.push_back(temp);
}
if (start >= tiles.size()) return;
for (int i = start;i < tiles.size();++i) {
dfs(res, tiles, temp + tiles[i], i + 1);
}
}
int numTilePossibilities(string tiles) {
vector<string> res;
string temp;
dfs(res, tiles, temp, 0);
map<string, bool> mp;
for (auto& s:res) {
sort(s.begin(), s.end());
do {
if (mp[s] == false) {
mp[s] = true;
}
} while (next_permutation(s.begin(), s.end()));
}
return mp.size() - 1;
}
};