お願い
- 数値のみを含む
2-9
文字列を指定すると、 それが表すことができるすべての文字の組み合わせを返します - 1はどの文字にも対応しません
例
- 「23」と入力します
- 输出:["ad"、 "ae"、 "af"、 "bd"、 "be"、 "bf"、 "cd"、 "ce"、 "cf"]
アイデア
- すべての可能な文字列を1つずつ再帰的に生成します
- s(数字)は、数字が生成できる文字列です
達成する
1 #include <vector> 2 #include <iostream> 3 #include < string > 4 #include <assert.h> 5 6 名前空間std を使用 ; 7 8 クラスソリューション{ 9 10 private : 11 const string letterMap [ 10 ] = { 12 " " 、 13 "" 、 14 " abc " 、 15 " def " 、 16 " GHI " 17 " JKL " 18は" のMnO " 19 " PQRS " 20は" TUV " 21が" WXYZ " 22はである }; 23は、24 ベクトル< ストリング > RES; 25 // 治療指数桁 26は、// S数字によって生成された文字列を保存します[0 ... index-1] 27 // 数字[index]に一致する文字を検索し、数字によって生成されたソリューションを取得します[0 ... index] 28 void findCombination(const string&digits、int index、const string&s){ 29 30 cout << index << " :" << s << endl; 31 32 // 终止条件 33 if(index == digits.size()){ 34 // s是一 个解、保存35 res.push_back(s); 36 cout << " get " << s << " 、return " << endl; 37 リターン; 40 文字 c = 数字[インデックス]; 41 assert(c> = ' 0 ' && c <= ' 9 ' && c!= ' 1 ' ); 42 文字の文字= letterMap [c- ' 0 ' ]; 43 44 for(int i = 0 ; i <letters.size(); i ++ ){ 45 cout << " digits [ " << index << " ] = " << c << "<< letters [i] << endl; 46 // 处理第index + 1位数字 47 findCombination(数字、インデックス+ 1、s + 文字[i]); 48 } 49 cout << " digits [ " << index << " ] = " << c << " 完了、" << endl; 50 リターン; 51 } 52 public : 53 vector < 文字列 > 初始化 56 res.clear(); 57 // 边界情事 58 if(digits == "" ) 59 return res; 60 61 findCombination(digits、0、"" ); 62 63は 解像度を返します。 64 } 65 }; 66 67 int main(){ 68 69 vector < string > res = Solution()。letterCombinations(" 23 " ); 70 のための(int型 I =0 ; i <res.size(); i ++ ) 71 cout << res [i] << endl; 72 73は 0を返し ます。 74 }
まとめ
- 本質はバックトラッキングであり、これは激しい列挙ソリューションです
- バックトラックは、再帰的に実装できるアルゴリズムのアイデアです。
- 複数のループとの違いは、処理される文字の長さが不明であることです。
- 動的プログラミングの本質は、効率を高めるためにバックトラックに基づいて改善することです
- 複雑さ:3 ^ n(O(2 ^ n)、n文字、数字ごとに3文字)
- 低効率、家庭用コンピュータn <20
関連した
- 93 IPアドレスの復元
- 131回文の分割
参考資料
再帰とバックトラックの違いは何ですか?区別する方法は?