最初のソリューションは、アナグラム間の結果の並べ替えは、同じでなければならない新しいソートがある場合には、新しいものではないがあるたびに新しいリストを作成ASCIIによるアレイのすべての文字列にありますソート、そして、リンクリストに同等のASCIIソート言葉、ストアに各リストをリンクリストを作成し、最終的にそれを返すように接続しています。
しかし、あまりにも多くの書き込み、その通過OJの最初の時間の複雑さは、第2の解決策は、今そこにあります
#include<iostream>
#include<map>
#include<string>
#include<vector>
using namespace std;
void func(vector<string>& str)
{
map<string, int> map1;
vector<vector<string>> vecvec;
int w = 0;
while (!str.empty())
{
vector<int> vec;
vec.resize(26);
int i = 0;
for (int j = 0; j < str[i].size(); ++j)
{
vec[str[i][j] - 'a']++;
}
string str1;
for (int k = 0; k < vec.size(); ++k)
{
str1 += to_string(vec[k]);
}
if (map1.find(str1) != map1.end())
{
auto it = map1.find(str1);
vecvec[(*it).second].push_back(str[i]);
}
else
{
map1.insert(make_pair(str1, w));
vector<string>* v = new vector<string>;
v->push_back(str[i]);
vecvec.push_back(*v);
w++;
}
++i;
}
}
私は2番目のコードの意味を説明し、このコードを実行していない
無一種であるが必要とされる第2の方法は、最初の効率よりも少し高くなっています
この質問は、再帰的な動的なプログラミングを行うために拡張することができます再帰を使用することである
再帰的なバージョンを書くために最初に
#include<iostream>
#include<vector>
#include<algorithm>
using namespace std;
int process(vector<vector<int>> vec,int row,int col)
{
int path = 1;
if (col > 0 && vec[row][col - 1] > vec[row][col]) //向左
path = max(path, process(vec, row, col - 1) + 1);
if (row > 0 && vec[row - 1][col] > vec[row][col]) //向上
path = max(path, process(vec, row - 1, col) + 1);
if (row < vec.size() - 1 && vec[row + 1][col] > vec[row][col]) //向下
path = max(path, process(vec, row + 1, col) + 1);
if (col < vec[0].size() - 1 && vec[row][col + 1] > vec[row][col]) //向右
path = max(path, process(vec, row, col + 1) + 1);
return path;
}
int func(vector<vector<int>> vec)
{
int maxsex = 0;
for (int row = 0; row < vec.size(); ++row)
{
for (int col = 0; col < vec[0].size(); ++col) //这里为什么是vec[0],而不是i其实是因为是一个矩阵,每一行的个数都是一样的
{
maxsex = max(maxsex,process(vec, row, col));
}
}
return maxsex;
}
int main()
{
vector<vector<int>> vec;
vector<int> vec1 = { 9, 9, 8 };
vector<int> vec2 = { 7, 6, 7 };
vector<int> vec3 = { 2, 1, 1 };
vec.push_back(vec1);
vec.push_back(vec2);
vec.push_back(vec3);
cout << func(vec) << endl; // 返回5 [1,6,7,8,9]
return 0;
}
原理は、ある
計画と言うの背後にあるダイナミック