問題描述:
算法基礎_遞歸_求楊輝三角第m行第n個數字(m,n都從0開始)
解題源代碼(這里打印出的是楊輝三角某一層的所有數字,沒用大數,所以有上限,這里只寫基本邏輯,要符合題意的話,把循環去掉就好):
import java.util.Scanner; /** * 求楊輝三角第m層第n個數字 * @author Administrator * */ public class Demo05 { public static int f(int m,int n) { if(n==0)return 1; if(m==0 || m==n)return 1; return f(m-1,n-1)+f(m-1,n);//只需要寫上規律語句即可 } public static void main(String[] args) { Scanner sc = new Scanner(System.in); int m = sc.nextInt(); for(int i = 0;i<m+1;i++) { System.out.print(f(m,i)+" "); } //System.out.println(f(3,2)); } }
解題思路:
因為楊輝三角的規律就是 要求的那個數字 = 上一行這個位置的數字 + 其前一個數字
這樣表達式就出來了,直接return就行
希望對大家有所幫助
以上