zoukankan      html  css  js  c++  java
  • 振兴中华--递归

    描述
    ×××参加了学校的趣味运动会,其中的一个项目是:跳格子。
    地上画着一些格子,每个格子里写一个字,如下所示:(也可参见下图)
    从我做起振
    我做起振兴
    做起振兴中
    起振兴中华
    比赛时,先站在左上角的写着“从”字的格子里,可以横向或纵向跳到相邻的格子里,但不能跳到对角的格子或其它位置。一直要跳到“华”字结束。
    要求跳过的路线刚好构成“从我做起振兴中华”这句话。
    请你帮助×××算一算他一共有多少种可能的跳跃路线呢?
    输出
    可能的总量n
    递归解法
    
    import java.util.*;
    public class problem {
    	public int count = 0;
    	public void f(int x, int y) {// 格子要么横 ,要么竖 两种情况 递归写两种横着一个 竖着一个
    		if (x == 1 && y == 1) {
    			count++;
    		} else {
    			if (x == 1) {// 到最边的时候只能有一种走法
    				count++;
    			} else if (y == 1) {// 到最边的时候只能有一种走法
    				count++;
    			} else {
    				f(x - 1, y);// 竖
    				f(x, y - 1);// 横
    			}
    		}
    	}
    	public static void main(String[] args) {
    		problem p = new problem();
    		p.f(5, 4);
    		System.out.println(p.count);
    	}
    }
    
    参考网上的视频 https://www.bilibili.com/video/av36899189/?p=5
    上面也可以用深度遍历来解
    还有非递归的方法 如下 用二维数组保存到每一个格有几种方法,每一个格都是它上面和它左边的数值相加
    
    import java.util.*;
    public class problem {
    	public int f(int x, int y) {// 格子要么横 ,要么竖 两种情况 递归写两种横着一个 竖着一个
    		int[][] arr = new int[x][y];
    		for (int i = 0; i < x; i++) {
    			arr[i][0] = 1;
    		}
    		for (int i = 0; i < y; i++) {
    			arr[0][i] = 1;
    		}
    		for (int i1 = 1; i1 < x; i1++) {
    			for (int i2 = 1; i2 < y; i2++) {
    				arr[i1][i2] = arr[i1 - 1][i2] + arr[i1][i2 - 1];
    			}
    		}
    		return arr[x - 1][y - 1];
    	}
    	public static void main(String[] args) {
    		problem p = new problem();
    		System.out.println(p.f(5, 4));
    	}
    }
    
  • 相关阅读:
    利用消息机制实现.NET AOP(面向方面编程)--通过RealProxy实现 zz
    A Taste of AOP from Solving Problems with OOP and Design Patterns (Part II) zz
    在.Net中使用异步(一)
    在.Net中使用异步(二)
    技术人员的误区(zz)
    A Taste of AOP from Solving Problems with OOP and Design Patterns (Part III) zz
    利用矩阵进行坐标系转换
    如何选择开源许可证[zz]
    .Net,你为什么会慢
    理解 Thread.Sleep 函数
  • 原文地址:https://www.cnblogs.com/cznczai/p/11148178.html
Copyright © 2011-2022 走看看