作者: 负雪明烛
id: fuxuemingzhu
个人博客: http://fuxuemingzhu.cn/


题目地址:https://leetcode.com/problems/satisfiability-of-equality-equations/

题目描述

Given an array equations of strings that represent relationships between variables, each string equations[i] has length 4 and takes one of two different forms: "a==b" or "a!=b". Here, a and b are lowercase letters (not necessarily different) that represent one-letter variable names.

Return true if and only if it is possible to assign integers to variable names so as to satisfy all the given equations.

Example 1:

Input: ["a==b","b!=a"]
Output: false
Explanation: If we assign say, a = 1 and b = 1, then the first equation is satisfied, but not the second. There is no way to assign the variables to satisfy both equations.

Example 2:

Input: ["b==a","a==b"]
Output: true
Explanation: We could assign a = 1 and b = 1 to satisfy both equations.

Example 3:

Input: ["a==b","b==c","a==c"]
Output: true

Example 4:

Input: ["a==b","b!=c","c==a"]
Output: false

Example 5:

Input: ["c==c","b==d","x!=z"]
Output: true

Note:

  1. 1 <= equations.length <= 500
  2. equations[i].length == 4
  3. equations[i][0] and equations[i][3] are lowercase letters
  4. equationsi is either ‘=’ or ‘!’
  5. equations[i][2] is ‘=’

题目大意

给了一连串的等式和不等式,判断这些等式和不等式能否同时都成立。

解题方法

DFS

这题最难的部分就是数据抽象,其实并不难:把每个字母当做一个节点,把等号代表两个节点之间有连接,把不等号代表两个节点之间没有连接。判断这样的图是否存在。

由此可见,我们首先可以根据等号关系,把这个网的所有节点之间的连接构成一个无向图。然后对于不等号,我们记性dfs搜索,判断等号两边的节点能不能有路。如果有路代表两者通过一定的等号关系能够相互转化,那么就不符合不等号关系,返回false;如果所有不等号两边的节点都没有路,那么返回true.

这个题直接搜索的话会超时,可以把已经访问过的节点保存下来,这样的话,等我们在搜索下一条路的时候不会走已经搜索过的节点。

python代码如下:

class Solution(object):
def equationsPossible(self, equations):
"""
:type equations: List[str]
:rtype: bool
"""
self.m = collections.defaultdict(list)
for eq in equations:
if eq[1] == '=':
self.m[eq[0]].append(eq[3])
self.m[eq[3]].append(eq[0])
for eq in equations:
if eq[1] == '!':
if self.find(set(), eq[0], eq[3]) or self.find(set(), eq[3], eq[0]):
return False
return True def find(self, visited, begin, end):
if begin in visited:
return False
visited.add(begin)
if begin == end:
return True
for n in self.m[begin]:
if self.find(visited, n, end):
return True
return False

并查集

判断两个点直接是否有连接的一个更为简单的方法就是使用并查集。如果两个节点的祖先相同,说明两者之间有路。

下面是一种并查集的写法,这个写法在查找某个节点的祖先的时候做了路径压缩,使得被查找节点直接挂载到了祖先上,这样下次查找的时候就不用搜索那么多了。而合并的这一步骤,是直接查找到两个节点的左右祖先,把其中一个的祖先设置成为了另一个。

不要太纠结,记住,对于a==b,无论是a的祖先设置成b、还是把b的祖先设置成a,都不想影响查找出来的a和b的祖先是同一个元素。

python代码如下:

class Solution(object):
def equationsPossible(self, equations):
"""
:type equations: List[str]
:rtype: bool
"""
dsu = DSU()
for eq in equations:
if eq[1] == '=':
dsu.u(ord(eq[0]) - ord('a'), ord(eq[3]) - ord('a'))
for eq in equations:
if eq[1] == '!':
if dsu.f(ord(eq[0]) - ord('a')) == dsu.f(ord(eq[3]) - ord('a')):
return False
return True class DSU(object):
def __init__(self):
self.m = range(26) def f(self, x):
if self.m[x] != x:
self.m[x] = self.f(self.m[x])
return self.m[x] def u(self, x, y):
px = self.f(x)
py = self.f(y)
self.m[px] = py

C++代码如下:

class Solution {
public:
bool equationsPossible(vector<string>& equations) {
init();
for (string& s : equations) {
if (s[1] == '=') {
u(s[0] - 'a', s[3] - 'a');
}
}
for (string& s : equations) {
if (s[1] == '!') {
if (f(s[0] - 'a') == f(s[3] - 'a'))
return false;
}
}
return true;
}
private:
int _fa[26]; void init() {
for (int i = 0; i < 26; ++i) {
_fa[i] = i;
}
}
int f(int x) {
if (_fa[x] == x) return x;
return _fa[x] = f(_fa[x]);
}
void u(int a, int b) {
int pa = f(a);
int pb = f(b);
_fa[pa] = pb;
}
};

日期

2019 年 2 月 21 日 —— 一放假就再难抓紧了

【LeetCode】990. Satisfiability of Equality Equations 解题报告(C++ & python)的更多相关文章

  1. LeetCode 990. Satisfiability of Equality Equations

    原题链接在这里:https://leetcode.com/problems/satisfiability-of-equality-equations/ 题目: Given an array equat ...

  2. 【LeetCode】299. Bulls and Cows 解题报告(Python)

    [LeetCode]299. Bulls and Cows 解题报告(Python) 作者: 负雪明烛 id: fuxuemingzhu 个人博客: http://fuxuemingzhu.cn/ 题 ...

  3. 【LeetCode】743. Network Delay Time 解题报告(Python)

    [LeetCode]743. Network Delay Time 解题报告(Python) 标签(空格分隔): LeetCode 作者: 负雪明烛 id: fuxuemingzhu 个人博客: ht ...

  4. 【LeetCode】518. Coin Change 2 解题报告(Python)

    [LeetCode]518. Coin Change 2 解题报告(Python) 作者: 负雪明烛 id: fuxuemingzhu 个人博客: http://fuxuemingzhu.cn/ 题目 ...

  5. 【LeetCode】474. Ones and Zeroes 解题报告(Python)

    [LeetCode]474. Ones and Zeroes 解题报告(Python) 作者: 负雪明烛 id: fuxuemingzhu 个人博客: http://fuxuemingzhu.cn/ ...

  6. 【LeetCode】731. My Calendar II 解题报告(Python)

    [LeetCode]731. My Calendar II 解题报告(Python) 作者: 负雪明烛 id: fuxuemingzhu 个人博客: http://fuxuemingzhu.cn/ 题 ...

  7. 【LeetCode】785. Is Graph Bipartite? 解题报告(Python)

    [LeetCode]785. Is Graph Bipartite? 解题报告(Python) 作者: 负雪明烛 id: fuxuemingzhu 个人博客: http://fuxuemingzhu. ...

  8. 【LeetCode】895. Maximum Frequency Stack 解题报告(Python)

    [LeetCode]895. Maximum Frequency Stack 解题报告(Python) 作者: 负雪明烛 id: fuxuemingzhu 个人博客: http://fuxueming ...

  9. 【LeetCode】764. Largest Plus Sign 解题报告(Python)

    [LeetCode]764. Largest Plus Sign 解题报告(Python) 作者: 负雪明烛 id: fuxuemingzhu 个人博客: http://fuxuemingzhu.cn ...

随机推荐

  1. python20判断变量是否存在

    python中检测某个变量是否有定义 第一种方法使用内置函数locals(): locals():获取已定义对象字典 'testvar' in locals().keys() 第二种方法使用内置函数d ...

  2. 毕业设计之mysql+主从复制+keepalived

    环境介绍 mysql_VIP:192.168.111.123 mysql_M!:192.168.111.151 mysql_M2:192.168.111.152 安装mysql可以查看 两个数据库都需 ...

  3. R 多图间距调整

    在R中多图画到一起的时候,各图间距通常默认的较远. 如下图: 1 par(mfcol=c(2,1)) 2 plot(1:100) 3 plot(1:100) 调整图片间距这时我们要用到par()函数中 ...

  4. 开始读 Go 源码了

    原文链接: 开始读 Go 源码了 学完 Go 的基础知识已经有一段时间了,那么接下来应该学什么呢?有几个方向可以考虑,比如说 Web 开发,网络编程等. 在下一阶段的学习之前,写了一个开源项目|Go ...

  5. 利用charles映射解决夜神模拟器安装xposed-v89-sdk25-x86.zip

    最近在玩xposed框架,前前后后搞了两天,浪费一个周末,总算把踩过的坑都踩了一遍.. 比如大家肯定遇到的的一个问题:夜神模拟器打开xposed安装器之后,为什么下载不了xposed-v89-sdk2 ...

  6. 学习java的第二十八天

    一.今日收获 1.java完全学习手册第三章算法的3.2排序,比较了跟c语言排序上的不同 2.观看哔哩哔哩上的教学视频 二.今日问题 1.快速排序法的运行调试多次 2.哔哩哔哩教学视频的一些术语不太理 ...

  7. Spark(十)【RDD的读取和保存】

    目录 一.文件类型 1.Text文件 2.Json文件 3.对象文件 4.Sequence文件 二.文件系统 1. MySQL 2. Hbase 一.文件类型 1.Text文件 读写 读取 scala ...

  8. MapStruct对象转换

    第一次看到 MapStruct 的时候, 我个人非常的开心.因为其跟我内心里面的想法不谋而合. 1 MapStruct 是什么? 1.1 JavaBean 的困扰 对于代码中 JavaBean之间的转 ...

  9. Can namespaces be nested in C++?

    In C++, namespaces can be nested, and resolution of namespace variables is hierarchical. For example ...

  10. OC-copy,单例

    总结 编号 主题 内容 一 NSFileManager NSFileManager介绍/用法(常见的判断)/文件访问/文件操作 二 集合对象的内存管理 集合对象的内存管理/内存管理总结 三 *copy ...