当前位置: 首页 > news >正文

leetcode 365 水壶问题

有一个水壶容量或者两个水壶加起来总容量为目标容量

总共有八种选择:第一种倒满x,第二种倒满y,第三种清空x,第四种清空y,第五种x 倒给 y y能装满 ,第六种 x 倒给 y x倒完, 。。。。

这里用深度遍历,时间超时

class Solution {public boolean canMeasureWater(int jug1Capacity, int jug2Capacity, int targetCapacity) {//深度递归//用一个visited map来判断 当前情况是否能成功,因此只需要置为false一次即可,不需要反复操作//存储水量,涉及到判断,重写写一个类来存储State state = new State(0, 0);ArrayList<State> states = new ArrayList<>();return dfs(jug1Capacity,jug2Capacity,targetCapacity,state,states);}private boolean dfs(int jug1Capacity, int jug2Capacity, int targetCapacity, State state, List states) {if (states.contains(state))return false;states.add(state);//结束条件if (state.x < 0 || state.y < 0 || state.x > jug1Capacity || state.y > jug2Capacity)return false;if (state.x == targetCapacity || state.y == targetCapacity || state.x + state.y == targetCapacity)return true;//总共有八种情况//第一种倒满x,第二种倒满y,第三种清空x,第四种清空y,第五种x 倒给 y y能装满 ,第六种 x 倒给 y x倒完, 。。。。if (dfs(jug1Capacity,jug2Capacity,targetCapacity,new State(jug1Capacity,state.y),states)|| dfs(jug1Capacity,jug2Capacity,targetCapacity,new State(state.x, jug2Capacity),states)||dfs(jug1Capacity,jug2Capacity,targetCapacity,new State(0, state.y),states)|| dfs(jug1Capacity,jug2Capacity,targetCapacity,new State(state.x, 0),states)|| dfs(jug1Capacity,jug2Capacity,targetCapacity,new State(state.x - (jug2Capacity - state.y), jug2Capacity),states)|| dfs(jug1Capacity,jug2Capacity,targetCapacity,new State(0, state.y + state.x),states)|| dfs(jug1Capacity,jug2Capacity,targetCapacity,new State(jug1Capacity, state.y - (jug1Capacity - state.x)),states)|| dfs(jug1Capacity,jug2Capacity,targetCapacity,new State(state.x + state.y, 0),states))return true;return false;}
}class  State{int x;int y;public State(int x, int y) {this.x = x;this.y = y;}@Overridepublic boolean equals(Object o) {if (this == o) return true;if (o == null || getClass() != o.getClass()) return false;State state = (State) o;return x == state.x && y == state.y;}@Overridepublic int hashCode() {return Objects.hash(x, y);}
}

http://www.lryc.cn/news/149465.html

相关文章:

  • django/CVE-2017-12794XSS漏洞复现
  • 【学习笔记】计算机视觉对比学习综述
  • 【Linux】fork函数的基础知识
  • 代码随想录算法训练营day48 | LeetCode 198. 打家劫舍 213. 打家劫舍 II 337. 打家劫舍 III
  • 【已解决】Java 后端使用数组流 Array.stream() 将数组格式的 Cookie 转换成字符串格式
  • Redis——》如何评估锁过期时间
  • 完整开发实现公众号主动消息推送,精彩内容即刻到达
  • 获取ip(公网和内网) 前端通过高德api获取位置信息
  • linux打开端口命令是什么
  • 从《孤注一掷》出发,聊聊 SSL 证书的重要性
  • 专题:曲面的切平面、法线
  • 数据结构:排序解析
  • Revit SDK:AutoJoin 自动合并体量
  • MYSQL(索引、事务)
  • 部署问题集合(二十三)设置Docker容器内的中文字符集,解决某些情况下中文乱码的问题
  • Web AP—PC端网页特效
  • Spring线程池ThreadPoolTaskExecutor使用
  • spring mvc的执行流程
  • docker作业
  • java实现本地文件转文件流发送到前端
  • 2020ICPC南京站
  • Linux 中的 chsh 命令及示例
  • JavaScript 数组如何实现冒泡排序?
  • ZooKeeper集群环境搭建
  • 【跟小嘉学 Rust 编程】二十、进阶扩展
  • pytorch学习过程中一些基础语法
  • 判断聚类 n_clusters
  • 基于深度学习的网络异常检测方法研究
  • SSM 基于注解的整合实现
  • 工具类APP如何解决黏性差、停留短、打开率低等痛点?