递归练习-House Robber问题求解

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/a_step_further/article/details/52497262

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


猜你喜欢

转载自blog.csdn.net/a_step_further/article/details/52497262