未通过的递归算法
杨辉三角
http://www.nowcoder.com/questionTerminal/8c6984f3dc664ef0a305c24e1473729e
归类为递归,所以采用递归操作,但是没有通过,只通过了70%的案列。
下面是代码:
import java.util.Scanner; public class Main { public static void main(String[] args) { Scanner scanner=new Scanner(System.in); int n=scanner.nextInt(); //前面是获取n,忽略不看 show(n); } //显示答案 public static void show(int num){ for (int i = 0; i <num ; i++) { for (int j = 0; j <=i ; j++) { if(i==j){ System.out.println(getBin(i,j)); }else { System.out.print(getBin(i,j)+" "); } } } } //递归 public static int getBin(int n,int k){ if(k==0||k==n){ return 1; }else{ return getBin(n-1,k-1)+getBin(n-1,k); } } }
动态规划:
import java.util.Scanner; public class Main{ public static int [][]array; public static void main(String[] args) { Scanner scanner=new Scanner(System.in); int n=scanner.nextInt(); array=new int[n+1][n+1]; show(n); } public static void show(int num){ for (int i = 0; i <num ; i++) { for (int j = 0; j <=i ; j++) { if(i==j){ System.out.println(getBin2(i,j)); }else { System.out.print(getBin2(i,j)+" "); } } } } //递归 public static int getBin(int n,int k){ if(k==0||k==n){ return 1; }else{ return getBin(n-1,k-1)+getBin(n-1,k); } } public static int getBin2(int n,int k){ for (int i = 0; i <=n ; i++) { for (int j = 0; j <=Math.min(i,k) ; j++) { if(j==0||j==i){ array[i][j]=1; }else { array[i][j]= array[i-1][j-1]+ array[i-1][j]; } } } return array[n][k]; } }