Leetcode 276. Paint Fence (Easy) (cpp)

Leetcode 276. Paint Fence (Easy) (cpp)

Tag: Dynamic Programming

Difficulty: Easy


/*

276. Paint Fence (Easy)

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

You have to paint all the posts such that no more than two adjacent 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.

*/
class Solution {
public:
	int numWays(int n, int k) {
		if (n == 0 || k == 0) {
			return 0;
		}
		pair<int, int> p1 = make_pair(0, k), p2;
		for (int i = 2; i <= n; i++) {
			if (i & 1) {
				p1.first = p2.second;
				p1.second = (p2.first + p2.second) * (k - 1);
			}
			else {
				p2.first = p1.second;
				p2.second = (p1.first + p1.second) * (k - 1);
			}
		}
		return n & 1 ? p1.first + p1.second : p2.first + p2.second;
	}
};



發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章