zoukankan      html  css  js  c++  java
  • [leetcode]House Robber1,2

    /**
     * 一、
     * 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.
     二、
     Note: This is an extension of House Robber.
    
     After robbing those houses on that street, the thief has found himself a new place for his thievery so that he will not get too much attention. This time, all houses at this place are arranged in a circle. That means the first house is the neighbor of the last one. Meanwhile, the security system for these houses remain the same as for those in the previous street.
    
     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.
     */
    /*
    * 动态规划的一般套路,创建数组记录到当前这家时可能得到的最大收入,有两种情况,偷这家:res[i-2] + nums[i],不偷这家:res[i-1]
    * 状态方程:两种情况取较大的
    * 第二题可以分两种情况考虑,一种是偷第一家,则最后一家不偷,第二种就是偷最后一家,第一家不偷,两种情况的较大者就是结果*/
    public class Q198HouseRobber {
        public int rob(int[] nums) {
            if (nums.length == 0 )
                return 0;
            int[] res = new int[nums.length+1];
            res[0] = 0;
            res[1] = nums[0];
            for (int i = 2; i < nums.length+1; i++) {
                res[i] = Math.max((res[i-2]+nums[i-1]),res[i-1]);
            }
            return res[nums.length];
        }
        public int rob2(int[] nums){
            if (nums.length == 0 )
                return 0;
            if (nums.length == 1)
                return nums[0];
            int[] res1 = new int[nums.length];
            int[] res2 = new int[nums.length+1];
            //包含第一家的情况,最后一家肯定没有,所以循环的次数减1
            res1[0] = 0;
            res1[1] = nums[0];
            for (int i = 2; i < nums.length; i++) {
                res1[i] = Math.max((res1[i-2]+nums[i-1]),res1[i-1]);
            }
            //不包含第一家的情况,
            res2[0] = 0;
            res2[1] = 0;
            for (int i = 2; i < nums.length+1; i++) {
                res2[i] = Math.max((res2[i-2]+nums[i-1]),res2[i-1]);
            }
            return Math.max(res1[res1.length-1],res2[res2.length-1]);
        }
    }
  • 相关阅读:
    linux进程管理类
    linux关机重启指令
    linux分区及磁盘挂载
    linux的运行级别
    property
    访问限制机制
    类的组合与封装
    继承与派生
    logging模块
    re模块
  • 原文地址:https://www.cnblogs.com/stAr-1/p/7486940.html
Copyright © 2011-2022 走看看