【LeetCode】433. Minimum Genetic Mutation 解题报告(Python & C++)
作者: 负雪明烛
id: fuxuemingzhu
个人博客: http://fuxuemingzhu.cn/
题目地址: https://leetcode.com/problems/minimum-genetic-mutation/description/
题目描述
A gene string can be represented by an 8-character long string, with choices from "A", "C", "G", "T"
.
Suppose we need to investigate about a mutation (mutation from “start” to “end”), where ONE mutation is defined as ONE single character changed in the gene string.
For example, "AACCGGTT"
-> "AACCGGTA"
is 1 mutation.
Also, there is a given gene “bank”, which records all the valid gene mutations. A gene must be in the bank to make it a valid gene string.
Now, given 3 things - start, end, bank, your task is to determine what is the minimum number of mutations needed to mutate from “start” to “end”. If there is no such a mutation, return -1.
Note:
- Starting point is assumed to be valid, so it might not be included in the bank.
- If multiple mutations are needed, all mutations during in the sequence must be valid.
- You may assume start and end string is not the same.
Example 1:
start: "AACCGGTT"
end: "AACCGGTA"
bank: ["AACCGGTA"]
return: 1
Example 2:
start: "AACCGGTT"
end: "AAACGGTA"
bank: ["AACCGGTA", "AACCGCTA", "AAACGGTA"]
return: 2
Example 3:
start: "AAAAACCC"
end: "AACCCCCC"
bank: ["AAAACCCC", "AAACCCCC", "AACCCCCC"]
return: 3
题目大意
给出了一个起始基因,一个结束基因,问能不能通过变换,每次变化当前基因的一位,并且变化后的这个基因在基因库中的为有效基因,最后变换成为end。如果不可以的话,返回-1.
题目没有给出变换的过程,如果有问题的话,看127. Word Ladder这个类似题目。
解题方法
基本和127. Word Ladder一模一样的,只不过把26个搜索换成了4个搜索,所以代码只用改变搜索的范围,以及最后的返回值就行了。
很显然这个问题是BFS的问题,同样是走迷宫问题的4个方向,代码总体思路很简单,就是利用队列保存每个遍历的有效的字符串,然后对队列中的每个字符串再次遍历,保存每次遍历的长度即可。每个元素进队列的时候,保存了到达这个元素需要的步数,这样能省下遍历和记录当前bfs长度部分代码。
时间复杂度是O(NL),空间复杂度是O(N).其中N是Bank中的单词个数,L是基因的长度。
class Solution(object):
def minMutation(self, start, end, bank):
"""
:type start: str
:type end: str
:type bank: List[str]
:rtype: int
"""
bfs = collections.deque()
bfs.append((start, 0))
bankset = set(bank)
while bfs:
gene, step = bfs.popleft()
if gene == end:
return step
for i in range(len(gene)):
for x in "ACGT":
newGene = gene[:i] + x + gene[i+1:]
if newGene in bank and newGene != gene:
bfs.append((newGene, step + 1))
bank.remove(newGene)
return -1
C++代码如下:
class Solution {
public:
int minMutation(string start, string end, vector<string>& bank) {
queue<string> q;
const int N = start.size();
q.push(start);
int step = 0;
while (!q.empty()) {
int size = q.size();
for (int s = 0; s < size; s++) {
auto cur = q.front(); q.pop();
if (cur == end) {
return step;
}
for (int i = 0; i < N; i++) {
for (char n : {'A', 'C', 'G', 'T'}) {
string next = cur.substr(0, i) + n + cur.substr(i + 1);
if (next == cur) continue;
for (auto it = bank.begin(); it < bank.end(); ++it) {
if (*it == next) {
q.push(next);
bank.erase(it);
break;
}
}
}
}
}
step += 1;
}
return -1;
}
};
参考资料:
http://www.cnblogs.com/grandyang/p/7653006.html
http://www.cnblogs.com/grandyang/p/4539768.html
日期
2018 年 9 月 29 日 —— 国庆9天长假第一天!
2018 年 12 月 28 日 —— 即将元旦假期
【LeetCode】433. Minimum Genetic Mutation 解题报告(Python & C++)的更多相关文章
- 【leetcode】433. Minimum Genetic Mutation
题目如下: 解题思路:我的思路很简单,就是利用BFS方法搜索,找到最小值. 代码如下: class Solution(object): def canMutation(self, w, d, c, q ...
- 【LeetCode】62. Unique Paths 解题报告(Python & C++)
作者: 负雪明烛 id: fuxuemingzhu 个人博客: http://fuxuemingzhu.cn/ 题目地址:https://leetcode.com/problems/unique-pa ...
- 【LeetCode】435. Non-overlapping Intervals 解题报告(Python)
[LeetCode]435. Non-overlapping Intervals 解题报告(Python) 作者: 负雪明烛 id: fuxuemingzhu 个人博客: http://fuxuemi ...
- 【LeetCode】397. Integer Replacement 解题报告(Python)
[LeetCode]397. Integer Replacement 解题报告(Python) 标签: LeetCode 题目地址:https://leetcode.com/problems/inte ...
- 【LeetCode】376. Wiggle Subsequence 解题报告(Python)
[LeetCode]376. Wiggle Subsequence 解题报告(Python) 作者: 负雪明烛 id: fuxuemingzhu 个人博客: http://fuxuemingzhu.c ...
- 【LeetCode】649. Dota2 Senate 解题报告(Python)
[LeetCode]649. Dota2 Senate 解题报告(Python) 作者: 负雪明烛 id: fuxuemingzhu 个人博客: http://fuxuemingzhu.cn/ 题目地 ...
- 【LeetCode】911. Online Election 解题报告(Python)
[LeetCode]911. Online Election 解题报告(Python) 作者: 负雪明烛 id: fuxuemingzhu 个人博客: http://fuxuemingzhu.cn/ ...
- 【LeetCode】886. Possible Bipartition 解题报告(Python)
[LeetCode]886. Possible Bipartition 解题报告(Python) 作者: 负雪明烛 id: fuxuemingzhu 个人博客: http://fuxuemingzhu ...
- 【LeetCode】36. Valid Sudoku 解题报告(Python)
[LeetCode]36. Valid Sudoku 解题报告(Python) 作者: 负雪明烛 id: fuxuemingzhu 个人博客: http://fuxuemingzhu.cn/ 题目地址 ...
随机推荐
- GraphScope 集群部署
GraphScope 集群部署 1 k8s集群搭建 大致步骤如下: 安装docker.在ubuntu上,可以简单的通过命令sudo apt install docker.io来安装. 安装kubele ...
- 日常Java 2021/10/28
Java lterator Java lterator(迭代器)不是一个集合,它是一种用于访问集合的方法,可用于迭代 ArrayList和HashSet等集合.lterator是Java迭代器最简单的 ...
- a这个词根
a是个词根,有三种意思:1. 以某种状态或方式,如: ablaze, afire, aflame, alight, aloud, alive, afloat等2. at, in, on, to sth ...
- accessory, accident
accessory 1. belt, scarf, handbag, Penny用rhinestone做的小首饰(Penny Blossom)都是accessory2. With default se ...
- 外网无法访问hdfs文件系统
由于本地测试和服务器不在一个局域网,安装的hadoop配置文件是以内网ip作为机器间通信的ip. 在这种情况下,我们能够访问到namenode机器, namenode会给我们数据所在机器的ip地址供我 ...
- Scala(七)【异常处理】
目录 一.try-catch-finally 二.Try(表达式).getOrElse(异常出现返回的默认值) 三. 直接抛出异常 一.try-catch-finally 使用场景:在获取外部链接的时 ...
- Scala(四)【集合基础入门】
目录 一.Array 二. List 三.Set 四.Tuple 五.Map 一.Array package com.bigdata.scala.day01 /** * @description: 不 ...
- 大数据学习day25------spark08-----1. 读取数据库的形式创建DataFrame 2. Parquet格式的数据源 3. Orc格式的数据源 4.spark_sql整合hive 5.在IDEA中编写spark程序(用来操作hive) 6. SQL风格和DSL风格以及RDD的形式计算连续登陆三天的用户
1. 读取数据库的形式创建DataFrame DataFrameFromJDBC object DataFrameFromJDBC { def main(args: Array[String]): U ...
- 源码分析-NameServer
架构设计 消息中间件的设计思路一般是基于主题订阅发布的机制,消息生产者(Producer)发送某一个主题到消息服务器,消息服务器负责将消息持久化存储,消息消费者(Consumer)订阅该兴趣的主题,消 ...
- 时光网内地影视票房Top100爬取
为了和艺恩网的数据作比较,让结果更精确,在昨天又写了一个时光网信息的爬取,这次的难度比艺恩网的大不少,话不多说,先放代码 # -*- coding:utf-8 -*-from __future__ i ...