|
| 1 | +想法:用 hash set紀錄已經出現過的字串,嘗試所有字串組合並檢查是否已經出現過,未出現過則加入字串 |
| 2 | +最後輸出 hash set 大小即可 |
| 3 | + |
| 4 | +Time Complexity : O(n!) for there are O(n!) possible strings |
| 5 | +Space Complexity : O(n!) for the hash set and the recursion |
| 6 | + |
| 7 | +class Solution { |
| 8 | +public: |
| 9 | + unordered_set<string> appear ; |
| 10 | + void constructTiles (vector<int>& frequency , string now) { |
| 11 | + for(int i = 0 ; i < 26 ; i++) { |
| 12 | + if ( frequency[i] > 0 ) { |
| 13 | + frequency[i]-- ; |
| 14 | + for(int insertindex = 0 ; insertindex <= now.size();insertindex++) { |
| 15 | + string newstr ; |
| 16 | + if (insertindex > 0) |
| 17 | + newstr += now.substr(0 , insertindex) ; |
| 18 | + newstr += ('A' + i) ; |
| 19 | + if (insertindex < now.size()) |
| 20 | + newstr += now.substr(insertindex) ; |
| 21 | + |
| 22 | + if ( appear.find(newstr) == appear.end() ) { |
| 23 | + appear.insert(newstr) ; |
| 24 | + constructTiles(frequency , newstr) ; |
| 25 | + } |
| 26 | + } |
| 27 | + frequency[i]++ ; |
| 28 | + } |
| 29 | + } |
| 30 | + } |
| 31 | + int numTilePossibilities(string tiles) { |
| 32 | + vector<int> frequency(26) ; |
| 33 | + for(auto &c : tiles) |
| 34 | + frequency[ c - 'A']++ ; |
| 35 | + constructTiles(frequency , "") ; |
| 36 | + return appear.size() ; |
| 37 | + } |
| 38 | +}; |
| 39 | + |
| 40 | +// 法二:只需考慮剩餘字母即可,用遞迴決定第 i 個字母填什麼,接著考慮 i + 1 ... n |
| 41 | +回傳剩餘字母可組成的種類數量 + 單獨該字母組成的一種字串 |
| 42 | + |
| 43 | +Time Complexity : O(n!) for the recursion |
| 44 | +Space Complexity : O(n!) for the recursion |
| 45 | + |
| 46 | +class Solution { |
| 47 | +public: |
| 48 | + int constructTiles (vector<int>& frequency , int size ) { |
| 49 | + int count = 0 ; |
| 50 | + for(int i = 0 ; i < 26 ; i++) { |
| 51 | + if ( frequency[i] > 0 ) { |
| 52 | + frequency[i]-- ; |
| 53 | + count += constructTiles(frequency , size + 1) + 1 ; |
| 54 | + frequency[i]++ ; |
| 55 | + } |
| 56 | + } |
| 57 | + return count ; |
| 58 | + } |
| 59 | + int numTilePossibilities(string tiles) { |
| 60 | + vector<int> frequency(26) ; |
| 61 | + for(auto &c : tiles) |
| 62 | + frequency[ c - 'A']++ ; |
| 63 | + return constructTiles(frequency , 0) ; |
| 64 | + } |
| 65 | +}; |
| 66 | + |
0 commit comments