2015年11月5日星期四

Leetcode 276 Paint Fence

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.
Solution 1: DP question. Maintain an array of same and diff. Transaction formula will be same[i]=diff[i-1]; diff[i]=(same[i-1]+diff[i-1])*(n-1). Optimize to O(1) space as below:
 public class Solution {  
   public int numWays(int n, int k) {  
     if (n==0) return 0;  
     int same=0, diff=k;  
     for (int i=1; i<n; i++) {  
       int pre=same;  
       same=diff;  
       diff=(pre+diff)*(k-1);  
     }  
     return same+diff;  
   }  
 }  

没有评论:

发表评论