1. 程式人生 > >遞迴練習-House Robber問題求解

遞迴練習-House Robber問題求解

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