回溯之组合总和,字符搜索

 

#include<iostream>
#include<vector>
#include<map>
#include<string>
#include<numeric>
using namespace std;
vector<vector<int>> res;
class solution
{
public:
	void test(int n,int T)
	{
		vector<int> v;
		dfs(v, n, T);
	}
private:
	void dfs(vector<int> &v, int n,int t)
	{
		if (v.size()<=3&&accumulate(v.begin(),v.end(),0) == t)
		{
			res.push_back(v);
			return;
		}
		else if (accumulate(v.begin(), v.end(), 0) > t)
		{
			return;
		}
		for (int i = 1; i <= n; i++)
		{
				v.push_back(i);
				dfs(v, n, t);
				v.pop_back();
		}
	}
};
int main()
{
	int n = 5,T=7;
	class solution a;
	a.test(n,T);
	for (int i = 0; i < res.size(); i++)
	{
		for (int j = 0; j < res[i].size(); j++)
			cout << res[i][j] << " ";
		cout << endl;
	}
	system("pause");
	return 0;
}
#include<iostream>
#include<vector>
#include<map>
#include<string>
#include<numeric>
using namespace std;
vector<vector<char>> res;
vector<vector<bool>> visit;
int m, n;
int b[4][2] = {
	{-1,0},
	{0, 1},
	{1,0},
	{0,-1}
};
class solution
{
public:
	bool test(string s)
	{
		m = res.size();
		n = res[0].size();
		visit = vector<vector<bool>>(m, vector<bool>(n, false));
		for (int i = 0; i < m; i++)
			for (int j = 0; j < n; j++)
				if (dfs(s, 0, i, j))
					return true;
		return false;

	}
private:
	bool IsTure(int x, int y)
	{
		if (x >= 0 && x < m&&y >= 0 && y < n)
			return true;
		else
			return false;
	}
	bool dfs(string s,int index,int x,int y)
	{
		if (index == s.size() - 1)
			return res[x][y] == s[s.size() - 1];
			
		if (res[x][y] == s[index])
		{
			visit[x][y] = true;
			for(int i = 0;i < 4; i++)
			{
				int newx, newy;
				newx = x + b[i][0];
				newy = y + b[i][1];
				if (IsTure(newx, newy) && !visit[newx][newy] && dfs(s, index + 1, newx, newy))
					return true;
				else
					return false;
			}
		}
		else
			return false;
	}
};
发布了98 篇原创文章 · 获赞 1 · 访问量 4493

猜你喜欢

转载自blog.csdn.net/weixin_40823740/article/details/103325714