admin管理员组文章数量:1558086
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);
}
}
版权声明:本文标题:递归练习-House Robber问题求解 内容由热心网友自发贡献,该文观点仅代表作者本人, 转载请联系作者并注明出处:https://m.elefans.com/xitong/1727342394a1109573.html, 本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌抄袭侵权/违法违规的内容,一经查实,本站将立刻删除。
发表评论