File tree Expand file tree Collapse file tree 1 file changed +39
-0
lines changed Expand file tree Collapse file tree 1 file changed +39
-0
lines changed Original file line number Diff line number Diff line change
1
+ # There is a fence with n posts, each post can be painted with one of the k colors.
2
+ #
3
+ # You have to paint all the posts such that no more than two adjacent fence posts have the same color.
4
+ #
5
+ # Return the total number of ways you can paint the fence.
6
+ #
7
+ # Note:
8
+ # n and k are non-negative integers.
9
+ #
10
+ # Example:
11
+ #
12
+ # Input: n = 3, k = 2
13
+ # Output: 6
14
+ # Explanation: Take c1 as color 1, c2 as color 2. All possible ways are:
15
+ #
16
+ # post1 post2 post3
17
+ # ----- ----- ----- -----
18
+ # 1 c1 c1 c2
19
+ # 2 c1 c2 c1
20
+ # 3 c1 c2 c2
21
+ # 4 c2 c1 c1
22
+ # 5 c2 c1 c2
23
+ # 6 c2 c2 c1
24
+
25
+
26
+ class Solution :
27
+ def numWays (self , n , k ):
28
+
29
+ if n == 0 :
30
+ return 0
31
+ if n == 1 :
32
+ return k
33
+
34
+ same , diff = k , k * (k - 1 )
35
+
36
+ for i in range (3 , n + 1 ):
37
+ same , diff = diff , (same + diff ) * (k - 1 )
38
+
39
+ return same + diff
You can’t perform that action at this time.
0 commit comments