GV

GeezerVison

The World Wide Web, restored to 800 pixels of glory.

Home|About|Gaming cabinet|Archives|How it works|Starter sites

On this site

  • Sign in
  • ActionsCI/CD and automation
  • CodespacesCloud development environments
  • All Features
  • Documentation
  • Training
  • Certifications
  • Build with Copilot
  • Customize Copilot
  • Integrations
  • Trending repos
  • GitHub Sponsors
  • Developer articles
  • Enterprises

This view

  • Original page
  • New address

GeezerVison is showing github.com — LeetCode/Dynamic_Programming/265.Paint-House-II at master · black128/LeetCode

Expand file tree

/

265.Paint-House-II

/
Copy path

Directory actions

More options

More options

Directory actions

More options

More options

Latest commit

 

History

History
History
 
 
/

265.Paint-House-II

/
Copy path

Folders and files

NameName
Last commit message
Last commit date

parent directory

..
265.Paint-House-II.cpp
265.Paint-House-II.cpp
 
 
265.Paint-House-II_v2.cpp
265.Paint-House-II_v2.cpp
 
 
Readme.md
Readme.md
 
 

Readme.md

265.Paint-House-II

本题比较正常的DP解法就是令dp[i][j]表示刷完第i个房子、且第i个房子刷第j种漆,此时所需要的全部代价。

此题可以做到o(N*K)的解法。这是因为我们在确定第i座房子刷第j种漆后,本质上只需要关心前面第i-1座房子刷完漆的最小代价是什么,再加上costs[i][j]即可。唯一需要考虑的就是:如果给第i-1座房子刷漆的最小代价所用的油漆也是第j种漆,和第i个房子所用的油漆重合了怎么办?遇到这种情况,我们需要同时也记录下刷完第i-1座房子第二最小代价及其油漆种类就行。

一个比较粗暴的方法就是,考虑刷完第i-1座房子之后,将所有的dp[i-1][k](k=0,1,2,...,K-1)排个序,记录下最小的两个值以及对应的油漆编号,比如说a和b。所以计算dp[i][j]时,如果j!=a,则dp[i][j]=dp[i-1][a]+costs[i][j];否则我们就要采用备选方案,即dp[i][j]=dp[i-1][b]+costs[i][j]

因为我们不能肯定最后一座房子会刷什么颜色,所以最后的答案是在dp[N-1][k](k=0,1,2,...,K-1)挑选最小值。

此题和1289. Minimum Falling Path Sum II本质一模一样。

Leetcode Link

You are visitor 01402792 — GeezerVison does not store the pages you look up.
Best viewed with Netscape Navigator 4.7 or Internet Explorer 6 at 800×600. No cookies required.