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;
    }

    @Override
    public 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;
    }

    @Override
    public int hashCode() {
        return Objects.hash(x, y);
    }
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值