LeetCode 256. Paint House
2017-01-11 10:36
323 查看
There are a row of n houses, each house can be painted with one of the three colors: red, blue or green. The cost of painting each house with a certain color is different. You have to paint all the houses such that no two adjacent houses have the same color.
The cost of painting each house with a certain color is represented by a n x 3 cost matrix. For example, costs[0][0] is the cost of painting house 0 with color red; costs[1][2] is the cost of painting house 1 with color green, and so on… Find the minimum cost to paint all houses.
Note:
All costs are positive integers.
思路:
1. 这代表一类题,遍历所有可能性,且遵循一定的约束条件。最直接的方法是,遍历所有可能性,找出最小cost,但这样的复杂度就是指数增长,o(2^n)。
2. 如何简化复杂度,减少不必要的运算?可以把问题看成是有层次的问题,这样就可以分割成小的问题,小的问题继续分成更小的问题,直到问题不能分割为止。和直接遍历把所有可能性平等的对待相比,这样有层次的方式,是把小问题解决了,大问题的解决就容易了,减少了遍历的可能性!因此,怎么看待或怎么建模这个问题,决定了采用什么方法解决这个问题。
3. 用DP,二维dp。找递推关系,小问题和大问题之间的逻辑联系!
2. 突然有个想法,应该设法总结一下,很多问题用简单粗暴的方法做,复杂度为什么很差?因此,需要借助一些辅助手段来回避这一类问题!
The cost of painting each house with a certain color is represented by a n x 3 cost matrix. For example, costs[0][0] is the cost of painting house 0 with color red; costs[1][2] is the cost of painting house 1 with color green, and so on… Find the minimum cost to paint all houses.
Note:
All costs are positive integers.
思路:
1. 这代表一类题,遍历所有可能性,且遵循一定的约束条件。最直接的方法是,遍历所有可能性,找出最小cost,但这样的复杂度就是指数增长,o(2^n)。
2. 如何简化复杂度,减少不必要的运算?可以把问题看成是有层次的问题,这样就可以分割成小的问题,小的问题继续分成更小的问题,直到问题不能分割为止。和直接遍历把所有可能性平等的对待相比,这样有层次的方式,是把小问题解决了,大问题的解决就容易了,减少了遍历的可能性!因此,怎么看待或怎么建模这个问题,决定了采用什么方法解决这个问题。
3. 用DP,二维dp。找递推关系,小问题和大问题之间的逻辑联系!
2. 突然有个想法,应该设法总结一下,很多问题用简单粗暴的方法做,复杂度为什么很差?因此,需要借助一些辅助手段来回避这一类问题!
int minCost(vector<vector<int>>& costs) { int n=costs.size(); vector<vector<int>> dp(n+1,vector<int>(3,0));//写完这一行,意识到是否可以不用新建array,直接在给定的2D array上做这个dp呢? for(int i=1;i<n;i++){ vector<int> cur=costs[i-1]; for(int j=0;i<3;j++){ dp[i][j]=dp[i][j]+min(cur[(j+1)%3],cur[(j+2)%3]); } } return min(min(costs.back()[0],costs.back()[1]),costs.back()[2]); }
相关文章推荐
- LeetCode-Add Binary
- [leetcode]Largest Rectangle in Histogram
- LeetCode Linked List Cycle && Linked List CycleII
- LeetCode "Unique Paths"
- Sort List[leetcode] 由归并排序的递归和循环,到本题的两种解法
- leetcode[155] Min Stack
- [LeetCode] Best Time to Buy and Sell Stock II
- leetcode之String to Integer (atoi)
- leetcode--Contains Duplicate
- Leetcode 131 Palindrome Partitioning 回文分割
- [LeetCode#116]Fraction to Recurring Decimal
- 【LeetCode】 Longest Substring Without Repeating Characters
- LeetCode 172:Factorial Trailing Zeroes
- leetcode之first bad version
- leetcode---Maximum Depth of Binary Tree
- LeetCode 122. Best Time to Buy and Sell Stock II(股票买卖)
- leetcode 二叉树中序遍历的递归和非递归实现
- LeetCode 136 Single Number (异或)
- LeetCode学习篇十五——Unique Binary Search Trees
- [leetcode]414. Third Maximum Number