Java数据结构(递归执行顺序、杨辉三角、斐波那契篇) (三)

2014-11-24 11:39:21 · 作者: · 浏览: 23
Trigo {

public static void main(String[] args) {
System.out.println(trigo(1));
System.out.println(trigo(2));
System.out.println(trigo(3));
System.out.println(trigo(4));

System.out.println("---");

System.out.println(trigoRecursion(1));
System.out.println(trigoRecursion(2));
System.out.println(trigoRecursion(3));
System.out.println(trigoRecursion(4));
}

/**
* 三角数字循环相加
* @param n
* @return
*/
public static int trigo(int n){
int total = 0;
while(n > 0){
total = total + n;
n--;
}
return total;
}

/**
* 三角数字递归相加
* @param n
* @return
*/
public static int trigoRecursion(int n){
if(n == 1)
return 1;
else
return n + trigoRecursion(--n);
}
}

package ch05Recursion;

public class Trigo {

public static void main(String[] args) {
System.out.println(trigo(1));
System.out.println(trigo(2));
System.out.println(trigo(3));
System.out.println(trigo(4));

System.out.println("---");

System.out.println(trigoRecursion(1));
System.out.println(trigoRecursion(2));
System.out.println(trigoRecursion(3));
System.out.println(trigoRecursion(4));
}

/**
* 三角数字循环相加
* @param n
* @return
*/
public static int trigo(int n){
int total = 0;
while(n > 0){
total = total + n;
n--;
}
return total;
}

/**
* 三角数字递归相加
* @param n
* @return
*/
public static int trigoRecursion(int n){
if(n == 1)
return 1;
else
return n + trigoRecursion(--n);
}
}

杨辉三角:


[java]
package ch05Recursion;

import java.util.Scanner;

public class YangHui {

public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
System.out.println("请输入将要显示的杨辉三角的行数(>=3):");
int i = sc.nextInt();
if(i <= 3){
System.out.println("请输入正确的值!");
System.exit(-1);
}
// 建立杨辉三角形模型
int yh[][] = new int[i][i];
// 根据杨辉三角形特点,先录入两条边上的值,皆为1;
for(int j = 0; j < i; j++){
yh[j][0] = 1;
yh[j][j] = 1;
}
// 根据杨辉三角形特点,填写其他值,完成整个杨辉三角形;
for(int j = 2; j < i; j++){
for(int n = 1; n < j; n++)
yh[j][n] = yh[j - 1][n - 1] + yh[j - 1][n];
}
// 打印杨辉三角形
for(int j = 0; j < i; j++){
for(int n = 0; n <= j; n++)
System.out.print(yh[j][n] + " ");
System.out.println();
}
}
}

package ch05Recursion;

import java.util.Scanner;

public class YangHui {

public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
System.out.println("请输入将要显示的杨辉三角的行数(>=3):");
int i = sc.nextInt();
if(i <= 3){
System.out.println("请输入正确的值!");
System.exit(-1);
}
// 建立杨辉三角形模型
int yh[][] = new int[i][i];
// 根据杨辉三角形特点,先录入两条边上的值,皆为1;
for(int j = 0; j < i; j++){
yh[j][0] = 1;
yh[j][j] = 1;
}
// 根据杨辉三角形特点,填写其他值,完成整个杨辉三角形;
for(int j = 2; j < i; j++){
for(int n = 1; n < j; n++)
yh[j][n] = yh[j - 1][n - 1] + yh[j - 1][n];
}
// 打印杨辉三角形
for(int j = 0; j < i; j++){
for(int n = 0; n <= j; n++)
System.out.print(yh[j][n] + " ");
System.out.println();
}
}
}

[java]
请输入将要显示的杨辉三角的行数(>=3):
8
1
1 1
1 2 1
1 3 3 1
1 4 6 4 1
1 5 10 10 5 1
1 6 15 20 15 6 1
1 7 21 35 35 21 7 1

请输入将要显示的杨辉三角的