198. House Robber I / House Robber III

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.

思路

  1. 根據(jù)題目项乒,因?yàn)椴荒苓B續(xù)偷兩家股缸,所以:有兩種可能惭每,偷當(dāng)前家可以最大獲利,或者不偷當(dāng)前家可以最大獲利。
  2. 偷當(dāng)前家的最大獲利 = max(【偷上一家的再上一家的maxProfit + 當(dāng)前家的財(cái)產(chǎn)】,不偷當(dāng)前家(即偷上一家的最大獲利))
  3. 用DP锋叨,dp[i] 表示偷第i家獲得的最大利益
  4. 初始化時(shí)含鳞,必須初始化dp[0], dp[1], 因?yàn)樵谇?code>dp[i]的時(shí)候城丧,我們必須知道偷上一家和偷上上家的獲利延曙。所以循環(huán)只能從2開始。0和1必須被初始化亡哄。
class Solution {
    public int rob(int[] nums) {
        //用DP
        //因?yàn)椴荒苓B續(xù)偷兩家枝缔,所以:有兩種可能,偷當(dāng)前價(jià)可以最大獲利蚊惯,或者不偷當(dāng)前價(jià)可以最大獲利
        //偷當(dāng)前家的最大獲利 = max(【偷上一家的再上一家的maxProfit + 當(dāng)前家的財(cái)產(chǎn)】愿卸,不偷當(dāng)前家(即偷上一家的最大獲利))
        //dp[i]: 偷第i家的最大獲利
        
        if (nums == null || nums.length == 0) return 0;
        if (nums.length == 1) return nums[0];
        if (nums.length == 2) return Math.max(nums[0], nums[1]);
        
        int[] dp = new int[nums.length];
        //循環(huán)只能從2開始,因?yàn)楸仨氈郎弦患?和 上上一家偷的情況
        dp[0] = nums[0];
        dp[1] = Math.max(nums[0], nums[1]);
        
        for (int i = 2; i < nums.length; i++) {
            dp[i] = Math.max(dp[i - 2] + nums[i], dp[i - 1]);
        }
        return dp[nums.length - 1];
    }
}

House Robber III

The thief has found himself a new place for his thievery again. There is only one entrance to this area, called the "root." Besides the root, each house has one and only one parent house. After a tour, the smart thief realized that "all houses in this place forms a binary tree". It will automatically contact the police if two directly-linked houses were broken into on the same night.

Determine the maximum amount of money the thief can rob tonight without alerting the police.

Example 1:

     3
    / \
   2   3
    \   \ 
     3   1

Maximum amount of money the thief can rob = 3 + 3 + 1 = 7.

Example 2:

     3
    / \
   4   5
  / \   \ 
 1   3   1

Maximum amount of money the thief can rob = 4 + 5 = 9.

思路 (遞歸)

與1思路相同截型,對(duì)于每個(gè)節(jié)點(diǎn)小偷都可以選擇偷或者不偷趴荸,那么對(duì)每個(gè)節(jié)點(diǎn)都返回一個(gè)int[2], result[0]表示偷這家能獲取的最大利益,result[1]表示不偷這家能獲取的最大利益宦焦。

  1. DFS搜索:遞歸停止條件发钝,root == null 時(shí)返回new int[2]:表示偷與不偷的獲利都為0.
  2. DFS計(jì)算其left和right child的獲利結(jié)果。
  3. 當(dāng)前節(jié)點(diǎn)偷(那么左右節(jié)點(diǎn)都不能偷): cur.val + leftProfit[1] + rightProftit[1]波闹。
  4. 當(dāng)前節(jié)點(diǎn)不偷(左右節(jié)點(diǎn)可以偷酝豪, 也可以不偷):Max(leftProfit[0], leftProfit[1]) + Max(rightProfit[0], rightProfit[1])
  5. 最后返回root節(jié)點(diǎn)偷或者不偷的最大值即可
class TreeNode {
  int val;
  TreeNode left;
  TreeNode right;
  
  public TreeNode(int val) {
    this.val = val;
    this.left = null;
    this.right = null;
  }
}


class Solution{
  static public int rob(TreeNode root) {
    if (root == null) return 0;
    
    int[] result = helper(root);
    return Math.max(result[0], result[1]);
  }
  
  static public int[] helper(TreeNode root) {
    if (root == null) {
      return new int[2];
    }
    
    // index 0: rob, index 1: not rob
    int[] leftProfit = helper(root.left);
    int[] rightProfit = helper(root.right);
    int[] result = new int[2];
    
    // rob: cannot rob the neighbor
    result[0] = root.val + leftProfit[1] + rightProfit[1];
    
    // not rob: can rob the neighbor, or not rob the neighbor; choose the bigger profit
    result[1] = Math.max(leftProfit[0], leftProfit[1]) + Math.max(rightProfit[0], rightProfit[1]);
    
    return result;
  }
  
  public static void main(String[] args) {
    TreeNode root = new TreeNode(3);
    TreeNode n1 = new TreeNode(2);
    TreeNode n2 = new TreeNode(3);
    root.left = n1;
    root.right = n2;
    
    TreeNode n3 = new TreeNode(4);
    TreeNode n4 = new TreeNode(5);
    
    n1.left = n3;
    n1.right = n4;
    
    TreeNode n5 = new TreeNode(1);
    n2.right = n5;
    
    System.out.println(rob(root));
    
  }
}
最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請(qǐng)聯(lián)系作者
  • 序言:七十年代末,一起剝皮案震驚了整個(gè)濱河市精堕,隨后出現(xiàn)的幾起案子孵淘,更是在濱河造成了極大的恐慌,老刑警劉巖歹篓,帶你破解...
    沈念sama閱讀 219,539評(píng)論 6 508
  • 序言:濱河連續(xù)發(fā)生了三起死亡事件瘫证,死亡現(xiàn)場(chǎng)離奇詭異,居然都是意外死亡庄撮,警方通過(guò)查閱死者的電腦和手機(jī)背捌,發(fā)現(xiàn)死者居然都...
    沈念sama閱讀 93,594評(píng)論 3 396
  • 文/潘曉璐 我一進(jìn)店門,熙熙樓的掌柜王于貴愁眉苦臉地迎上來(lái)重窟,“玉大人载萌,你說(shuō)我怎么就攤上這事惧财⊙采龋” “怎么了?”我有些...
    開封第一講書人閱讀 165,871評(píng)論 0 356
  • 文/不壞的土叔 我叫張陵垮衷,是天一觀的道長(zhǎng)厅翔。 經(jīng)常有香客問(wèn)我,道長(zhǎng)搀突,這世上最難降的妖魔是什么刀闷? 我笑而不...
    開封第一講書人閱讀 58,963評(píng)論 1 295
  • 正文 為了忘掉前任,我火速辦了婚禮,結(jié)果婚禮上甸昏,老公的妹妹穿的比我還像新娘顽分。我一直安慰自己,他們只是感情好施蜜,可當(dāng)我...
    茶點(diǎn)故事閱讀 67,984評(píng)論 6 393
  • 文/花漫 我一把揭開白布卒蘸。 她就那樣靜靜地躺著,像睡著了一般翻默。 火紅的嫁衣襯著肌膚如雪缸沃。 梳的紋絲不亂的頭發(fā)上,一...
    開封第一講書人閱讀 51,763評(píng)論 1 307
  • 那天修械,我揣著相機(jī)與錄音趾牧,去河邊找鬼。 笑死肯污,一個(gè)胖子當(dāng)著我的面吹牛翘单,可吹牛的內(nèi)容都是我干的。 我是一名探鬼主播蹦渣,決...
    沈念sama閱讀 40,468評(píng)論 3 420
  • 文/蒼蘭香墨 我猛地睜開眼县恕,長(zhǎng)吁一口氣:“原來(lái)是場(chǎng)噩夢(mèng)啊……” “哼!你這毒婦竟也來(lái)了剂桥?” 一聲冷哼從身側(cè)響起忠烛,我...
    開封第一講書人閱讀 39,357評(píng)論 0 276
  • 序言:老撾萬(wàn)榮一對(duì)情侶失蹤,失蹤者是張志新(化名)和其女友劉穎权逗,沒(méi)想到半個(gè)月后美尸,有當(dāng)?shù)厝嗽跇淞掷锇l(fā)現(xiàn)了一具尸體,經(jīng)...
    沈念sama閱讀 45,850評(píng)論 1 317
  • 正文 獨(dú)居荒郊野嶺守林人離奇死亡斟薇,尸身上長(zhǎng)有42處帶血的膿包…… 初始之章·張勛 以下內(nèi)容為張勛視角 年9月15日...
    茶點(diǎn)故事閱讀 38,002評(píng)論 3 338
  • 正文 我和宋清朗相戀三年师坎,在試婚紗的時(shí)候發(fā)現(xiàn)自己被綠了。 大學(xué)時(shí)的朋友給我發(fā)了我未婚夫和他白月光在一起吃飯的照片堪滨。...
    茶點(diǎn)故事閱讀 40,144評(píng)論 1 351
  • 序言:一個(gè)原本活蹦亂跳的男人離奇死亡胯陋,死狀恐怖,靈堂內(nèi)的尸體忽然破棺而出袱箱,到底是詐尸還是另有隱情遏乔,我是刑警寧澤,帶...
    沈念sama閱讀 35,823評(píng)論 5 346
  • 正文 年R本政府宣布发笔,位于F島的核電站盟萨,受9級(jí)特大地震影響,放射性物質(zhì)發(fā)生泄漏了讨。R本人自食惡果不足惜捻激,卻給世界環(huán)境...
    茶點(diǎn)故事閱讀 41,483評(píng)論 3 331
  • 文/蒙蒙 一制轰、第九天 我趴在偏房一處隱蔽的房頂上張望。 院中可真熱鬧胞谭,春花似錦垃杖、人聲如沸。這莊子的主人今日做“春日...
    開封第一講書人閱讀 32,026評(píng)論 0 22
  • 文/蒼蘭香墨 我抬頭看了看天上的太陽(yáng)。三九已至泉瞻,卻和暖如春脉漏,著一層夾襖步出監(jiān)牢的瞬間,已是汗流浹背袖牙。 一陣腳步聲響...
    開封第一講書人閱讀 33,150評(píng)論 1 272
  • 我被黑心中介騙來(lái)泰國(guó)打工侧巨, 沒(méi)想到剛下飛機(jī)就差點(diǎn)兒被人妖公主榨干…… 1. 我叫王不留,地道東北人鞭达。 一個(gè)月前我還...
    沈念sama閱讀 48,415評(píng)論 3 373
  • 正文 我出身青樓司忱,卻偏偏與公主長(zhǎng)得像,于是被迫代替她去往敵國(guó)和親畴蹭。 傳聞我的和親對(duì)象是個(gè)殘疾皇子坦仍,可洞房花燭夜當(dāng)晚...
    茶點(diǎn)故事閱讀 45,092評(píng)論 2 355

推薦閱讀更多精彩內(nèi)容