Paint Fence--Leetcode

Source: Internet
Author: User

There is a fence with n posts, each post can be painted with one of the K colors.

You had to paint all the posts such that no more than and the fence posts have the same color.

Return the total number of ways you can paint the fence.

Note:
N and k are non-negative integers.

Idea: DP.

Set P (i) to indicate the number of cases from the first poster to the Zhang Hai report.

Initial condition: P (0) = 0,p (1) = K.

When n=2, there are two cases: 1) The second Zhang Hai the color of the newspaper differs from the first, altogether K * (k-1) kind of situation; 2) The colors of the two posters are the same, altogether the K-type situation. So P (2) = k + k* (k-1).

When N>2, it is assumed that the current is the Zhang Hai report, there are two cases: 1) The Zhang Hai of the first and the previous color, the total is P (i-1) * (k-1) of the situation; 2) The Zhang Hai is the same as the color of the previous one, which is the case of P (i-2) * (k-1).

So P (i) = P (i-2) * (k-1) + P (i-1) * (k-1).

In the implementation, we do not need to use an array to record all the results, we only need P (i-2) and P (i-1) values, so you can use the variable slow to record the value of P (i-2), with fast to record the value of P (i-1).

1 classSolution {2  Public:3     intNumways (intNintk) {4         if(n = =0)returnN;5         if(n = =1)returnK;6         intslow =K;7         intFast = slow + slow * (K-1);8          for(inti =3; I <= N; i++) {9             intCur = slow * (K-1) + Fast * (K-1);Tenslow =fast; OneFast =cur; A         } -         returnfast; -     } the};

Paint Fence--Leetcode

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.