@waigx Thanks, now it makes sense. Very nice. So while I have the totals for n and n-1, you have partials for just n. Same number of variables, but very different meaning.

Would be a little clearer with variable names s and d. Then it would be easier to remember their meaning when reading the code. I guess mine could be clearer as well, although I like sequential variable names for sequential values.

Anyway, just a little variation of yours:

def numWays(self, n, k):
a, s = n and k, 0
for _ in range(n-1):
a, s = a*k - s, a - s
return a

a: number of all ways to paint the fences (i.e., the sum of your a and b)

s: number of ways to paint the fences and end with twice the same color (i.e., your a)

Edit: Oh, haha, looking back at other solutions, I see I actually used the and trick in another one :-) https://discuss.leetcode.com/post/83789