Ole*_*hov 9 algorithm dynamic-programming combinatorics
有一个有n个帖子的围栏,每个帖子都可以涂上一种k颜色.您必须绘制所有帖子,使得不超过两个相邻的栅栏柱具有相同的颜色.返回可以绘制栅栏的总方式.
diff - 具有不同颜色的组合的数量,
相同 - 具有相同颜色的组合的数量,
n - 发布的数量,
k - 颜色的数量.
对于n = 1:
diff = k;
same = 0;
Run Code Online (Sandbox Code Playgroud)
对于n = 2:
diff = k * (k - 1);
same = k;
Run Code Online (Sandbox Code Playgroud)
对于n = 3:
diff = (k + k * (k - 1)) * (k - 1);
same = k * (k - 1);
Run Code Online (Sandbox Code Playgroud)
最后的公式是:
diff[i] = (diff[i - 1] + diff[i - 2]) * (k - 1);
same[i] = diff[i - 1];
Run Code Online (Sandbox Code Playgroud)
我理解如何找到same[i],但我不明白如何找到diff[i].你能解释一下这个公式diff[i]吗?
Bet*_*eta 15
total[i] = diff[i] + same[i] (definition)
diff[i] = (k - 1) * total[i-1]
= (k - 1) * (diff[i-1] + same[i-1])
= (k - 1) * (diff[i-1] + diff[i-2])
Run Code Online (Sandbox Code Playgroud)
这是组合论的论点.
让我们根据问题陈述的规则diff[i, c]绘制i帖子的方式数量,以便最后一个围栏涂上颜色c.
我们有:
diff[i, c] = diff[i - 1, c'] + diff[i - 2, c''], c' != c OR c'' != c
Run Code Online (Sandbox Code Playgroud)
对于c我们绘制的每一个i,前一个可以以a结束c' != c(在这种情况下我们不关心前一个是什么),或者第二个以前可以以a结束c'' != c(在这种情况下我们不关心以前是什么)是),或两者兼而有之.
有k - 1可能c' != c和k - 1为c'' != c.所以我们可以c从复发中删除并简单地写:
diff[i] = (k - 1) * (diff[i - 1] + diff[i - 2])
Run Code Online (Sandbox Code Playgroud)
这是你拥有的.
该解决方案涉及详细的解释。请务必看一下。
public class PaintingFence {
public static int paintFence(int n, int k) {
//if there is 0 post then the ways to color it is 0.
if(n == 0) return 0;
//if there is one 1 post then the way to color it is k ways.
if(n == 1) return k;
/**
* Consider the first two post.
* case 1. When both post is of same color
* first post can be colored in k ways.
* second post has to be colored by same color.
* So the way in which the first post can be colored with same color is k * 1.
*
* case 2. When both post is of diff color
* first post can be colored in k ways.
* second post can be colored in k-1 ways.
* Hence the ways to color two post different is k * (k - 1)
*/
int same = k * 1;
int diff = k * (k -1);
/**
* As first 2 posts are already discussed, we will start with the third post.
*
* If the first two post are same then to make the third post different, we have
* k-1 ways. Hence same * (k-1)
* [same=k, so same * k-1 = k*(k-1) = diff => Remember this.]
*
* If the first two posts are different then to make the third different, we also have
* k - 1 ways. Hence diff * (k-1)
*
* So to make third post different color, we have
* same * (k-1) + diff * (k-1)
* = (same + diff) * (k-1)
* = k-1 * (same + diff)
*/
for(int i=3;i <=n; i++) {
int prevDiff = diff;
diff = (same + diff) * (k - 1); //as stated above
/**
* to make the third color same, we cannot do that because of constraint that only two
* posts can be of same color. So in this case, we cannot have to same color so it has to be
* diff.
*/
same = prevDiff * 1;
}
return same + diff;
}
public static void main(String[] args) {
System.out.println(paintFence(2, 4));
System.out.println(paintFence(3, 2));
}
}
Run Code Online (Sandbox Code Playgroud)