🔗 leetcode.com/problems/le…
题目
- 给 N 个字符,都是大写字母,字母可能重复
- 给出这些字符可以生成的所有字符串的个数
思路
- 最开始想要用组合数学的思路,后来写代码使用 dfs 回溯
- 枚举递归出口,即可以组成字符串的长度
- 枚举每一位字符的可能性,统计时进行去重判断
代码
class Solution {
public:
unordered_set<string> st
void dfs(unordered_map<char, int>& mp, int dst, string& tmp) {
if (dst == tmp.size()) {
st.insert(tmp)
return
}
for (auto item : mp) {
char ch = item.first
int cnt = item.second
if (cnt == 0) continue
mp[ch]--
tmp += ch
dfs(mp, dst, tmp)
mp[ch]++
tmp.pop_back()
}
}
int numTilePossibilities(string tiles) {
unordered_map<char, int> mp
string tmp
for (auto ch : tiles) {
mp[ch]++
}
int n = tiles.size()
for (int i = 1
dfs(mp, i, tmp)
}
return st.size()
}
}