import java.util.Scanner; public class Main { // 使用动态规划解法 // 状态转移方程 dp[i]=dp[i-1]+dp[i-2] public static void main(String[] args) { Scanner scanner = new Scanner(System.in); int n = scanner.nextInt(); // n+2 是为了防止数组下标越界,如输入1时 int[] dp = new int[n+2]; dp[1]= 1; dp[2] = 2; for (int i = 3; i <= n; i++) dp[i]=dp[i-1]+dp[i-2]; System.out.println(dp[n]); } }
本人使用的是组合数C(n,m)的方法来求的,虽然麻烦,但是很好理解。代码如下:
import java.math.BigInteger;
import java.util.Scanner;
public class Main {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
while (scanner.hasNext()) {
int n = scanner.nextInt();
BigInteger count = new BigInteger("0");
int x;
for (int y = 0; y <= n / 2; y++) { //y: 两阶 x:一阶
x = n - 2 * y;
if (y == 0 || x == 0) {
count = count.add(BigInteger.valueOf(1));
} else {
count = count.add(zuhe(y, x + y)); //总步数中两阶的取法
}
}
scanner.close();
}
public static BigInteger jc(int n) { //求n的阶乘
BigInteger sum = new BigInteger("0");
if (n == 1) {
sum = BigInteger.valueOf(1);
} else {
sum = BigInteger.valueOf(n).multiply(jc(n - 1));
}
return sum;
}
public static BigInteger zuhe(int n, int m) { //求组合数C(n,m)
return (jc(m).divide(jc(n).multiply(jc(m-n))));
}
}
package com.mytest.mymain; import java.io.*; public class Main{ public static void main(String[] args) throws Exception{ java.util.Scanner sc=new java.util.Scanner(System.in);//001 String str; while((str=sc.nextLine())!=null){ //002 int n=Integer.parseInt(str); long[] result=new long[n+2]; result[1]=1; result[2]=2; if(n==1 || n==2 ){ System.out.println(result[n]); }else{ for(int i=3;i<=n;i++){ result[i]=result[i-1]+result[i-2]; } System.out.println(result[n]); } } /* BufferedReader br = new BufferedReader(new InputStreamReader(System.in)); String str; while((str=br.readLine())!=null){ int n=Integer.parseInt(str); long[] result=new long[n+2]; result[1]=1; result[2]=2; if(n==1 || n==2 ){ System.out.println(result[n]); }else{ for(int i=3;i<=n;i++){ result[i]=result[i-1]+result[i-2]; } System.out.println(result[n]); } }*/ } } 备注:为何用Scanner 自己线下可以,但是这个上面却不通过,看来对输入输出流还不够了解,需要进一步学习,欢迎精通的人,给出关于用Scanner不通过的原因。代码就两处不同,001和002处。
import java.util.Scanner;