深度优先遍历-基因变异

这里使用了深度优先遍历的的算法。每一层递归都有for循环,我们可以拿for循环和相关的限制条件所排列组合。

class Solution {
public:
	int minMutation(string start, string end, vector<string>& bank) {
		if (start.size() != end.size()) {
			return -1;
		}

		if (start==end) {
			contin_str.emplace_back(end);
			//m++;
			//if (m==2) {
			//	cout << "debug" << " ";
			//}
			if ((contin_str.size()-1) < result && isSingleChange(contin_str)) {
				//if (result==3) {
				//	cout << "debug" << " ";
				//}
				result = contin_str.size()-1;
				//cout << result << " ";	
			}
			contin_str.pop_back();
		}
		int len_cs = contin_str.size();
		if (len_cs > 1 && !isSingleChange(contin_str)) {
			return -1;
		}
		for (int i = 0; i < bank.size(); i++) {
			if (find(index.begin(), index.end(),i)==index.end()) {
				contin_str.emplace_back(start);
				if (isSingleChange(contin_str)) {
					index.emplace_back(i);
					minMutation(bank[i], end, bank);
					index.pop_back();
				}
				contin_str.pop_back();
			}
		}
		if (result<INT_MAX) {
			return result;
		}
		else {
			return -1;
		}
	}
	bool isSingleChange(vector<string> &vec) {
		int len_cs = vec.size();
		if (len_cs<2) {
			return true;
		}
		bool isCurrent = false;
		int i = 0;
		int j = 0;
		while (len_cs>1 && i < vec[len_cs - 1].size() && j < vec[len_cs - 2].size()) {
			if (vec[len_cs - 1][i] != vec[len_cs - 2][j]) {
				count++;
			}
			i++;
			j++;
		}
		if (count == 1) {
			isCurrent = true;
			count = 0;
		}
		else {
			count = 0;
		}
		return isCurrent;
	}
public:
	vector<string> contin_str;
	vector<int> index;
	int result = INT_MAX;
	int count = 0;
	int m = 0;
};
int main()
{
	Solution sol;
	vector<string> bank = { "ABC","ABE","ACE" };
	int result = sol.minMutation("ABC", "ACE", bank);
	cout << result << " ";
	system("pause");
}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值