Rectangular footprint (dp) Algorithm

problem

We can use 2 small rectangle 1 of sideways or vertically to cover a larger rectangle.
Will the use of n 2
small rectangle 1 coverage without overlap a large rectangle 2 * n, the
total number of ways?

analysis

这种问题上来找不到规律,是啥啊?
Can first draw a few pictures, look for the law?
就相当于解数学题,肯定是有什么规律的?

  • n=1 Case 1
  • n=2 Case 2

Here Insert Picture Description

  • ·n=3
    Here Insert Picture Description
  • n=4
    Here Insert Picture Description
    To summarize the above rules, can be found n pendulum method and d of the two front n-1and n-2related pendulum method, i.e.F(n)=F(n-1)+F(n-2)

This is the meager number of columns ah concubinage

Code implementation (recursive version)

  public int RectCover(int target) {

        if(target<1)
            return 0;
        if(target==1){
            return 1;
        }
        if(target==2){
            return 2;
        }

        return RectCover(target-1)+RectCover(target-2);

    }

Code implementation (loop version)

 public int RectCover2(int target){

        if(target<1){
            return 0;
        }

        if(target==1){
            return 1;
        }

        if(target==2){
            return 2;
        }

        int preNum = 2;
        int prepreNum = 1;
        int result = 0;
        for(int i=3;i<=target;i++){
            result = preNum+prepreNum;
            prepreNum=preNum;
            preNum=result;
        }
        return result;
    }
He published 198 original articles · won praise 20 · views 20000 +

Guess you like

Origin blog.csdn.net/ZHOUJIAN_TANK/article/details/104904796