标签:数论,dfs
题目
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.
思路
- 如果给定字符串长度, 比如“A“A”A“B”B”可以组成的字符串个数,容易想到用排列组合的公式
- 此题不给定长度,可以用dfs求出所有情况
- 因为dfs过程可能出现重复状态,用set记录所有可能的状态,为了让相同状态的好比较,开始时对字符串进行排序操作。这样相同的字串(字符全部相同)的序列必然一致
code dfs+排列组合
class Solution {
public:
int fact[8] = {1, 1, 2, 6, 24, 120, 720, 5040 };
set<string> st;
int dfs(string& tiles, string seq, int postfix){
// cout << seq << "--"<<endl;
if (postfix>=tiles.length()){
if(st.find(seq) != st.end()) return 0;
vector<int> cnt(26, 0);
for(auto ch : seq) {
// cout<<ch<<endl;
cnt[ch-'A'] ++;
}
int ans = fact[seq.length()];
for(auto ct : cnt) {
ans /= fact[ct];}
st.insert(seq);
return ans;
}
return dfs(tiles, seq, postfix+1) + dfs(tiles, seq + tiles[postfix], postfix+1);
}
int numTilePossibilities(string tiles) {
sort(begin(tiles), end(tiles));
string string1="";
string1 += tiles[0];
//cout<<"--"<<string1<<endl;
return dfs(tiles, "", 1) + dfs(tiles,string1, 1) - 1;
}
};
小结
c++的char和string
-
char to string的错误写法
string str = "" + 'c'; //error string str = 'c'; //error
-
char to string 的正确写法
string str = ""; str += 'c'; str.push_back('c');
C++的map和set判断是否存在某个值
-
map
map<int, int> mp; if (mp.count(key) > 0) cout << "key exits" << endl;
-
set
set<int> st; if(st.find(key) != end(st)) cout << " key in set " <<endl;