CodeBook
  • Introduction
  • Array
    • Maximum Product of Three Numbers
    • Set Mismatch
    • Find the Duplicate Number
    • Find All Duplicates in an Array
    • Find All Numbers Disappeared in an Array
    • Missing Number
    • Single Number
    • Find Difference
    • Find the Celebrity
    • Word Distance
    • Product of Array Except Self
  • Binary Search
    • First Bad Version
    • Search in a Big Sorted Array
    • Search Range
    • Find the Peak
    • Maximum Number in Mountain Sequence
    • Search in Rotated Sorted Array
    • Find Minimum in Rotated Sorted Array
    • Search a 2D Matrix
    • Search a 2D Matrix II
    • Smallest Rectangle Enclosing Black Pixels
    • [Binary Search] Merge Two Sorted Array
    • Single Element in a Sorted Array
  • Two Pointers
    • 1 Forward
      • Moving Zeros
      • Remove Elements
      • Remove Duplicated
      • Longest Continuous Increasing Subsequence
      • Replace all Occurrences of String AB with C
    • 2 Oppsite
      • Rotate Array
      • Container With Most Water
      • Trapping Rain Water
      • Triangle Count
    • 3 Sliding Windows
      • Permutation in String
      • Find All Anagrams in a String
      • Longest Substring with At Most K Distinct Characters
      • Max Consecutive Ones II
      • Minimum Size Subarray Sum
      • Longest Substring Without Repeating Characters
      • Minimum Window Substring
      • Subarrays with K Different Integers
    • 4 Partition
      • Color Sort
      • Color Sort II
      • Partition Array
    • # Sum
      • Two Sum
      • Two Sum - Unique Pairs
      • Two Sum - Less Or Equal
      • Two Sum - Greater Than Target
      • Two Sum - Closest
      • Two Sum - Difference
      • Two Sum - Data Structure Design
      • Three Sum
      • Three Sum With Multiplicity
      • Three Sum Smaller
      • Three Sum - Triangle Count
      • Four Sum
  • BFS
    • 1 Traverse
      • Number of Islands
      • Clone Gragh
      • Number of Distinct Islands
      • Pacific Atlantic Water Flow
      • Surrounded Regions
      • Walls and Gates
      • Max Area of Island
    • 2 Shortest
      • 01 Matrix
      • Knight Shortest Path
      • Shortest Distance from All Buildings
      • Best Meet Point
      • Shortest Bridge
      • Snakes and Ladders
      • Bus Route
  • DFS
    • 0 Basic
      • Subsets
      • Subsets II
      • Permutations
      • Permutations II
      • Prev/Next Permutation
      • Kth Permutation
      • Permutation Index
      • Combination Sum
      • Combination Sum II
      • Combination Sum III
      • Combination
      • Path Sum
    • 1 Enumeration
      • Cartesian Product
      • Letter Combinations of a Phone Number
      • Split String
      • Palindrome Partitioning
      • Expression Add Operators
      • Target Sum
      • Restore IP Addresses
      • Generate Parentheses
      • Generalized Abbreviation
      • Remove Invalid Parentheses
      • Letter Case Permutation
      • Factor Combinations
      • Find the Missing Number II
    • 2 Search
      • N-Queens
      • Sudoku
      • Employee Importance
      • Increasing Subsequences
      • Nested List Weight Sum
    • 3 Flood Fill
      • Flood Fill
      • Number of Enclaves
    • 4 Path
      • Longest Increasing Path in a Matrix
      • Unique Paths III
    • 5 Memo
      • Knight Dialer
      • Regular Expression Matching
      • Wildcard Matching
    • # Word Big Four
      • Word Break
      • Word Break II
      • Word Pattern
      • Word Pattern II
      • Word Search
      • Word Search II
      • Word Ladder
      • Word Ladder II
  • Tree
    • 0 Binary Search Tree
      • Validate Binary Search Tree
      • Recover Binary Search Tree
      • Minimum Absolute Difference in BST
      • Find Mode in Binary Search Tree
      • Verify Preorder Sequence in Binary Search Tree
      • Unique Binary Search Trees
      • Count of Smaller Numbers After Self
      • Trim a Binary Search Tree
      • Closest Binary Search Tree Value
      • Closest Binary Search Tree Value II
    • 1 Traversal
      • Binary Tree Inorder Traversal
      • Binary Tree Preorder Traversal
      • Binary Tree Postorder Traversal
      • Binary Tree Level Order Traversal
    • 2 Divide and Conquer
      • Balanced Binary Tree
      • Max/Min Depth of Binary Tree
      • Diameter of Tree
      • DiffSum
      • Find Leaves of Binary Tree
    • 3 SubTree
      • Same/Symmetric Tree
      • TreeIsomorphism
      • Subtree of Another Tree
      • Find Duplicate Subtrees
      • Most Frequent Subtree Sum
      • Minimum Subtree
      • Subtree with Maximum Average
      • Equal Tree Partition
      • Flip Binary Tree To Match Preorder Traversal
    • 4 Path
      • Path Sum
      • Path Sum II
      • Path Sum III
      • Path Sum IV
      • Path Sum with Digits Representation
      • Binary Tree Paths
      • Binary Tree Longest Consecutive Sequence
      • Binary Tree Longest Consecutive Sequence II
      • Binary Tree Maximum Path Sum
      • Sum Root to Leaf Numbers
      • Boundary of Binary Tree
      • Smallest String Starting From Leaf
    • 5 Level Order
      • Level Order Traversal
      • Maximum Width of Binary Tree
      • Binary Tree Right Side View
      • Binary Tree Vertical Order Traversal
    • 6 LCA
      • LCA
      • LCA II
      • LCA III
      • LCA IV
      • Smallest Deepest Subtree
      • LCA of a BST
      • Cousins in Binary Tree
    • 7 Build Tree
      • Build Maximum Binary Tree
      • Convert Sorted List to Binary Search Tree
      • Serialize Deserialize
      • Verify Preorder Serialization of a Binary Tree
      • Construct Binary Tree from Traversals
    • 8 Distance
      • Closest Leaf in a Binary Tree
      • All Nodes Distance K in Binary Tree
    • 9 Structure
      • Flatten Binary Tree to Linked List
      • Binary Tree Upside Down
      • BST to Doubly LinkedList
      • Populating Next Right Pointers in Each Node
      • Populating Next Right Pointers in Each Node II
      • Invert Binary Tree
    • # N-ary Tree
  • String
    • 1 Pattern
      • Is Subsequence
      • One Edit Distance
      • Backspace String Compare
    • 2 Implementation
      • Reverse
      • Find the Closest Palindrome
      • Reverse Words in a String
      • Text Justification
    • 3 Substring
      • Implement Str
      • Longest Substring with At Least K Repeating Characters
      • Longest Common Prefix
    • 4 Number
      • Maximum Swap
      • Add Strings
      • Nth Digit
      • Compare Version Numbers
      • String to Integer (atoi)
      • Integer to English Words
      • Integer to Roman
      • Roman to Integer
      • Multiply Strings
      • Reverse Integer
    • 5 Decode
      • Decode String
      • Encode and Decode Strings
    • 6 Palindrome
      • Valid Palindrome
      • Valid Palindrome II
      • Palindrome Number
      • Palindrome Linked List
      • Palindromic Substrings
      • Palindrome Permutation
      • Palindrome Partitioning
      • Find Longest Palindromic Substring
      • Longest Palindromic Subsequence
      • Longest Palindromic Substrings
    • 7 Evaluation
      • Solve the Equation
      • Simplify Path
      • Valid Number
    • 8 Binary String
      • Count Binary Substrings
    • 9 Parenthesis
      • Valid Parenthesis String
      • Valid Parentheses
  • Data Structures
    • 0 Design
      • LRU
      • LFU
    • 1 LinkedList
      • Merge Sort
      • Find Cycle
      • Palindrome Linked List
      • Remove Duplicates
      • Flatten a Multilevel Doubly Linked List
      • Copy List with Random Pointer
    • 2 Stack
      • Min Stack
      • Max Stack
      • Implement Queue by Stacks
      • Implement Stack by Queues
    • 3 Queue/Deque
      • Moving Average
      • Design Circular Queue
      • Design Circular Deque
    • 4 Heap
      • Median for Data Stram
      • Kth Largest Data Stream
      • Top K Words
      • Top K Elements
      • Kth Smallest Number in Sorted Matrix
    • 5 Interval
      • Merge Intervals
      • Insert Interval
      • Non-overlapping Intervals
      • Maximum Length of Pair Chain
      • Meeting Room
      • Merge Two Sorted Interval List
      • Merge K Sorted Interval List
      • Intersection of Two Sorted Intervals
      • Meeting Room II
    • 6 Matrix
      • Multiply Sparse Matrix
      • Matrix Diagonal Traverse
      • Valid Sudoku
      • Spiral Matrix
    • 7 Iterator
      • Flatten 2D Vector
      • Pair Iterator
      • Peeking Iterator
      • Zigzag Iterator
    • 8 Hash
      • Design HashSet
      • Design HashMap
      • Hash Function
      • ReHash
      • Consistent Hash
      • Bloom Filter
      • Robin-Karp Algorithm
  • Advanced Data Structures
    • 1 Trie
      • Implement Trie
      • Stream of Characters
    • 2 Union Find
      • Number of Islands II
      • [Union Find]Graph Connect Tree
      • Minimum Spanning Tree
      • Bricks Falling When Hit
      • Most Stones Removed with Same Row or Column
      • Satisfiability of Equality Equations
    • 3 Monotonous Stack
      • Increasing Triplet Subsequence
      • Largest Rectangle in Histogram
      • Maximal Rectangle
      • Remove K Digits
      • Remove Duplicate Letters
      • Next Greater Element I
      • Next Greater Element II
    • 4 TreeSet/TreeMap
      • My Calendar I
      • My Calendar II
    • 5 Random
      • Shuffle an Array
      • Random Pick with Weight
      • Random Pick Index
    • 6 Binary Index Tree
    • 7 Segment Tree
      • Range Sum Query - Mutable
  • Graph
    • 1 General
      • Graph Deep Copy
    • 2 Topological Sorting
      • Course Schedule
      • Sequence Reconstruction
      • Alien Dictionary
    • 3 Bipartition
      • Is Graph Bipartition
      • Possible Bipartition
    • Detect Cycle in an Undirected Graph
    • Shortest Path in Undirected Graph
    • All Paths From Source to Target
    • Graph Valid Tree
    • Number of Connected Components in an Undirected Graph
    • Minimum Height Trees
  • Dynamic Programming
    • 0 Basic DP
      • Triangle
      • House Robber
      • House Robber II
      • Paint Fence
      • Paint House
    • 1 Sequence DP
      • Decode Ways
    • 2 Match Sequence DP
      • Edit Distance
      • K Edit Distance
      • Longest Common Subsequence
      • Minimum Swaps To Make Sequences Increasing
      • Scramble String
    • 3 Interval DP
      • Burst Ballons
      • Stone Game
    • 4 Matrix DP
      • Number Of Corner Rectangles
      • Max Square
      • Longest Increasing Path in a Matrix
    • 5 Backpack
      • K-Sum
      • Backpack1-01
      • Backpack2-01
      • Backpack4-Complete
      • Backpack3-Complete
      • Backpack7-Multiply
    • 6 Game DP
      • Predict the Winner
      • Can I Win
      • Coins In Line I
      • Coins In Line II
      • Coins In Line III
  • Common Methods
    • 1 Presum
      • Subarray Sum Equals K
      • Continuous Subarray Sum
      • Path Sum II
      • Min/Max Subarry
      • Contiguous 01-Array
      • Flip 01String to Monotone Increasing
      • Maximum Sum of Two Non-Overlapping Subarrays
    • 2 Bucket
      • Maximum Gap
    • 3 Simulation
      • Pour Water
    • 4 Buffer
      • Read N Characters Given Read4 II - Call multiple times
      • Read N Characters Given Read4
      • Third Maximum Number
    • 5 Merge/Union
      • Merge k Sorted Lists
      • Merge k Sorted Arrays
      • Merge k Sorted Intervals
      • Intersection of Three Sorted Array
      • Intersection of Two Arrays
      • Intersection of Two Arrays II
    • 6 Geometry
      • Max Points on a Line
    • 7 Math
      • GCD
      • Matrix Coordinate
      • Sqrt(x)
      • Divide Two Integers
      • pow(x, n)
    • 8 Sorting
      • Merge Sort
      • Quick Sort
      • Quick Select
  • Design/OOD
    • Design Rate Limiter
    • Design Hit Counter
    • Design Twitter
    • Design MapWithExpiration
    • Design Tiny URL
  • Appendix
    • Java Built-in
      • Comparator
      • Stream
      • String Pool
    • Multithreading
      • Synchronized
      • Producer-Consumer
      • CountDownLatch
      • Semaphore
      • Thread Pool
      • DeadLock
      • Inter-thread Communication
Powered by GitBook
On this page
  • Example
  • Note
  1. Dynamic Programming
  2. 0 Basic DP

House Robber

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 andit 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 tonightwithout alerting the police.

Example

Given[3, 8, 4], return8.

Note

这是一道典型的序列型的动态规划。f[i]代表路过完第i家的时候, 最多能有多少钱。一般求什么,f[i]就是什么。 对于i=n的时候,我们有两个选择, 就是抢或者不抢:

  • 抢的话,最后是i=n-2的钱数加上第n家的钱数

  • 不抢的话, 钱数等于i=n-1的钱数

2D:

public int rob(int[] num) {  
    int[][] dp = new int[num.length + 1][2];  
    for (int i = 1; i <= num.length; i++) {  
        dp[i][0] = Math.max(dp[i - 1][0], dp[i - 1][1]);  
        dp[i][1] = num[i - 1] + dp[i - 1][0];  
    }  
    return Math.max(dp[num.length][0], dp[num.length][1]);  
}

dp这个二维数组代表盗窃前i栋房子带来的最大收益,其中第二维一共有两个选择分别是0和1。0代表不盗窃第i栋房子,1代表盗窃第i栋房子。换句话就是说,dp[i][0]代表盗窃前i栋房子的最大收益,但是不包括第i栋房子的(因为没有盗窃第i栋房子),而dp[i][0]代表盗窃前i栋房子的最大收益,其中包括了第i栋房子的(因为第i栋房子被盗窃了)。

其实对一栋房子来说,结果无非是两种,被盗窃和没被窃。所以说,才会有之前分0和1两种情况进行讨论。如果第i栋房子没被盗窃的话,那么dp[i][0] = dp[i-1][0]和dp[i-1][1]中的最大值。这个比较好理解,如果第i栋房子没被窃,那么最大总收益dp[i][0]一定和dp[i-1][0],dp[i-1][1]这两个之中最大的相同。而假若第i栋房子被窃,那么dp[i][1]一定等于第num[i-1](注意,这里的i是从1开始的,所以i-1正好对应num中的第i项,因为num中的index是从0开始的)+dp[i-1][0],因为第i栋房子已经被窃了,第i-1栋房子肯定不能被窃,否则会触发警报,所以我们只能取dp[i-1][0]即第i-1栋房子没被窃情况的最大值。循环结束,最后返回dp[num.length][0]和dp[nums.length][1]较大的一项。

数组[80, 7, 9, 90, 87]按上面的做法得到每步的结果, 选i和不选i的结果

       80      7      9      90      87
不选i   0     (80)    80      89     80+90
选i   (80)     7     (89)   (80+90) (87+89)

换点数字和顺序:

       80      9      7       3      60
不选i   0     (80)    80      87      87
选i   (80)     9     (87)   (80+3) (87+60)

我们发现, 对于每一个i, 影响后面能用到的, 只有选i和不选i两个决策结果中比较大的那个, 所以我们可以只存一个, f[i]代表路过完第i家的时候, 最多能有多少钱. 就是以下算法:

1D:

public class Solution {
    /**
     * @param A: An array of non-negative integers.
     * return: The maximum amount of money you can rob tonight
     */
    //---方法一---
    public long houseRobber(int[] A) {
        // write your code here
        int n = A.length;
        if (n == 0)
            return 0;
        long []res = new long[n+1];


        res[0] = 0;
        res[1] = A[0];
        for (int i = 2; i <= n; i++) {
            res[i] = Math.max(res[i-1], res[i-2] + A[i-1]);
        }
        return res[n];
    }
}

之后呢, 我们发现, 对于某个状态c,假设它是奇数位的状态, 它前面有奇状态a和偶状态b:

 ...  a       b       c  ...
 ... 奇1     偶1      奇2  ...

它的状态只和它前面的一个奇状态和一个偶状态有关, 所以我们可以只存三个变量:

         奇1 和 偶1 推出 奇2

可是由于在奇2状态结果一出现的时候, 奇1结果就没啥用了, 可以被立即替换, 所以我们就可以只存一对奇偶的状态, 即两个变量, 如下:

滚动数组:

public long houseRobber(int[] A) {
        // write your code here
        int n = A.length;
        if (n == 0)
            return 0;
        long []res = new long[2];

        res[0] = 0;
        res[1] = A[0];
        for (int i = 2; i <= n; i++) {
            res[i%2] = Math.max(res[(i-1)%2], res[(i-2)%2] + A[i-1]);
        }
        return res[n%2];
    }
}

这就是滚动数组, 或者叫做滚动指针的空间优化.

利用常量进行滚动:

public long houseRobber(int[] A) {
    // write your code here
    int n = A.length;
    if (n == 0)
        return 0;

    long twoPrev = 0;
    long onePrev = A[0];
    for (int i = 2; i <= n; i++) {
        long curr = Math.max(onePrev, twoPrev + A[i - 1]);
        twoPrev = onePrev;
        onePrev = curr;
    }
    return onePrev;
}
PreviousTriangleNextHouse Robber II

Last updated 6 years ago