递归练习-House Robber问题求解

这篇博客探讨了LeetCode上的第198题——House Robber问题。该问题涉及计算在不触发相邻报警的情况下,能够抢劫的最大金额。博主通过递归方法详细解释了解题思路,旨在帮助读者理解如何解决此类问题。
摘要由CSDN通过智能技术生成

LeetCode上第198题,题目如下

You are a professional robber planning to rob houses along a street. Each house has a certain amount of money stashed, the only constraint stopping you from robbing each of them is that adjacent houses have security system connected and it will automatically contact the police if two adjacent houses were broken into on the same night.

Given a list of non-negative integers representing the amount of money of each house, determine the maximum amount of money you can rob tonight without alerting the police.

这首题适合拿来做递归的练习。个人代码如下:

public class Main {

    public static void main(String[] args) {
        //给定一个数组
        int[] houses = {1, 2, 3, 40, 50, 34, 2, 3, 4, 98, 3};

        //求解最大值
        int result = rob(houses);
        System.out.println("能抢到的最高金额为: " + result);

    }

    //为了解决这个问题,我们自顶向下思考, 假设从后面往前面抢, 对于每个位置, 有两种选择: 抢当前的家庭、不抢当前的家庭。于是这个位置上的最优解就是两种情形下的较大值
    //定义一个函数来求解处于位置n时的最优解
    static int solve(int n, int[] space) {
        if (n == 0) {
            return space[0];
        } else if (n == 1) {
            return Math.max(space[1], space[0]);
        } else {
            return Math.max(space[n] + solve(n - 2, space), 0 + solve(n - 1, space));
        }
    }


    //定义抢劫函数
    static int rob(int[] nums) {
        return solve(nums.length - 1, nums);
    }
}


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值