Skip to content
体验新版
项目
组织
正在加载...
登录
切换导航
打开侧边栏
梦境迷离
Cs Summary Reflection
提交
c1dd9c28
C
Cs Summary Reflection
项目概览
梦境迷离
/
Cs Summary Reflection
10 个月 前同步成功
通知
4
Star
1
Fork
0
代码
文件
提交
分支
Tags
贡献者
分支图
Diff
Issue
0
列表
看板
标记
里程碑
合并请求
0
DevOps
流水线
流水线任务
计划
Wiki
0
Wiki
分析
仓库
DevOps
项目成员
Pages
C
Cs Summary Reflection
项目概览
项目概览
详情
发布
仓库
仓库
文件
提交
分支
标签
贡献者
分支图
比较
Issue
0
Issue
0
列表
看板
标记
里程碑
合并请求
0
合并请求
0
Pages
DevOps
DevOps
流水线
流水线任务
计划
分析
分析
仓库分析
DevOps
Wiki
0
Wiki
成员
成员
收起侧边栏
关闭侧边栏
动态
分支图
创建新Issue
流水线任务
提交
Issue看板
前往新版Gitcode,体验更适合开发者的 AI 搜索 >>
提交
c1dd9c28
编写于
8月 01, 2020
作者:
S
sweeneycai
浏览文件
操作
浏览文件
下载
电子邮件补丁
差异文件
Add official solution of Leetcode_365.
上级
5de738cd
变更
1
隐藏空白更改
内联
并排
Showing
1 changed file
with
38 addition
and
0 deletion
+38
-0
scala-leetcode/src/main/scala/io/github/sweeneycai/Leetcode_365.scala
...de/src/main/scala/io/github/sweeneycai/Leetcode_365.scala
+38
-0
未找到文件。
scala-leetcode/src/main/scala/io/github/sweeneycai/Leetcode_365.scala
浏览文件 @
c1dd9c28
/* Licensed under Apache-2.0 (C) All Contributors */
package
io.github.sweeneycai
import
scala.annotation.tailrec
/**
* 365. 水壶问题(Medium)
* 有两个容量分别为 x升 和 y升 的水壶以及无限多的水。能否通过使用这两个水壶,从而可以得到恰好 z升 的水?
...
...
@@ -17,6 +19,10 @@ package io.github.sweeneycai
* @since 2020-3-23
*/
object
Leetcode_365
extends
App
{
/**
* Martin 在 Coursera 课程上讲解的函数式解法,在 Leetcode 提交会超出内存限制,但仍具有学习意义
*/
def
canMeasureWater
(
x
:
Int
,
y
:
Int
,
z
:
Int
)
:
Boolean
=
{
val
game
=
new
Pouring
(
Vector
(
x
,
y
))
// 使用`take(1)`在找到一个符合条件的路径之后就停止计算
...
...
@@ -95,6 +101,38 @@ object Leetcode_365 extends App {
}
}
/**
* 官解Scala版,双百
*/
def
canMeasureWater2
(
x
:
Int
,
y
:
Int
,
z
:
Int
)
:
Boolean
=
{
@tailrec
def
helper
(
possible
:
Vector
[(
Int
,
Int
)],
visited
:
Set
[(
Int
,
Int
)])
:
Boolean
=
{
if
(
possible
.
exists
(
contains
))
true
else
if
(
possible
.
isEmpty
)
false
else
{
val
next
=
possible
.
flatMap
(
moves
).
filter
(!
visited
.
contains
(
_
))
println
(
next
)
helper
(
next
,
visited
++
next
)
}
}
def
contains
(
tuple
:
(
Int
,
Int
))
:
Boolean
=
tuple
.
_1
==
z
||
tuple
.
_2
==
z
||
tuple
.
_1
+
tuple
.
_2
==
z
def
moves
(
tuple
:
(
Int
,
Int
))
:
Vector
[(
Int
,
Int
)]
=
{
val
fromAToB
=
math
.
min
(
tuple
.
_1
,
y
-
tuple
.
_2
)
val
fromBToA
=
math
.
min
(
tuple
.
_2
,
x
-
tuple
.
_1
)
Vector
[(
Int
,
Int
)]()
.+:(
0
->
tuple
.
_2
)
.+:(
tuple
.
_1
->
0
)
.+:(
tuple
.
_1
->
y
)
.+:(
x
->
tuple
.
_2
)
.+:((
tuple
.
_1
-
fromAToB
,
tuple
.
_2
+
fromAToB
))
.+:((
tuple
.
_1
+
fromBToA
,
tuple
.
_2
-
fromBToA
))
}
helper
(
Vector
(
0
->
0
),
Set
())
}
val
pouring
=
new
Pouring
(
Vector
(
3
,
5
))
println
(
pouring
.
solutions
(
6
).
toList
)
println
(
canMeasureWater
(
3
,
5
,
1
))
...
...
编辑
预览
Markdown
is supported
0%
请重试
或
添加新附件
.
添加附件
取消
You are about to add
0
people
to the discussion. Proceed with caution.
先完成此消息的编辑!
取消
想要评论请
注册
或
登录