Paint House — LeetCode 256 Python Solution
- Problem
- #256
- Pattern
- Dynamic Programming
- Reading time
- 2 min
- Source
- leetcode.com
The problem
There is a row of n houses, where each house can be painted one of three colors: red, blue, or green. The cost of painting each house with a certain color is different.
Example
- Input
- costs = [[17,2,17],[16,16,5],[14,3,19]]
- Output
- 10
- Explanation
- Paint house 0 into blue, paint house 1 into green, paint house 2 into blue.
Python solution
class Solution:
def minCost(self, costs: List[List[int]]) -> int:
a = b = c = 0
for ca, cb, cc in costs:
a, b, c = min(b, c) + ca, min(a, c) + cb, min(a, b) + cc
return min(a, b, c)Complexity
| Measure | Complexity |
|---|---|
| Time | O(n·m) (typical) |
| Space | O(n·m) or optimized auxiliary |
Pattern: Dynamic Programming
Define a state, write the transition, and stop recomputing the same subproblem. LeetCode 256. Paint House is filed here on both counts: the reference solution below belongs to the algorithm family this hub collects, and LeetCode tags it Dynamic Programming.
The dynamic programming guide has the Python template for the pattern and the 481 LeetCode problems that use it.
Related problems
Frequently asked questions
- How hard is LeetCode 256. Paint House?
- LeetCode 256. Paint House is rated Medium on LeetCode.
- What topics does LeetCode 256. Paint House cover?
- LeetCode 256. Paint House is tagged Array and Dynamic Programming on LeetCode.
- Is LeetCode 256. Paint House a premium problem?
- Yes. LeetCode 256. Paint House is a LeetCode Premium problem, so the full statement and test cases require a paid LeetCode subscription.