跟左神一起练算法

在这里插入图片描述
第一种解法就是将数组中的每一个字符串按照ASCII进行排序,变形词之间的排序结果肯定是一致的,假如出现了新的排序,那就新建一个链表,每次新出现一个没有的排序,那么就新建一个链表来存放,把ASCII排序相等的单词放到一个链表中,最后再将每个链表连接起来返回,就可以了。

但是第一种写法的时间复杂度太大,所以oj过不去,现在就有第二种解法

#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;
	}
}

我也没有跑这段代码,解释一下第二种代码的意思
在这里插入图片描述
第二种方法比第一种的效率高一点就是在不需要排序上

在这里插入图片描述
这道题是使用递归来做的,递归就可以引申到动态规划
先写一个递归版本

#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;
}

原理就是,
在这里插入图片描述
动态规划后面再说

发布了230 篇原创文章 · 获赞 28 · 访问量 9310

猜你喜欢

转载自blog.csdn.net/weixin_43767691/article/details/103640343
今日推荐