✅作者简介:我是18shou,一名即将秋招的java实习生
✨个人主页:_18shou
🔥系列专栏:牛客刷题专栏
目录
描述
思路
题中要求的是 空间复杂度 O(1) ,很明显使用递归是行不通的,我们先改成非递归的看一下(这种复杂度也是不行的,我们先看一下代码
import java.util.Scanner;
public class Main {
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
int num = in.nextInt();
int[] dp = new int[num + 1];
dp[1] = 1;
dp[2] = 1;
for (int i = 3; i <= num; i++) {
dp[i] = dp[i - 1] + dp[i - 2];
}
System.out.println(dp[num]);
}
}
通过上面代码我们可以看到当前值只和数组的前两个值有关,在往前面的就无关了,所以我们没必要申请一个数组,直接使用两个变量即可,这样空间复杂度就满足要求了
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
int num = in.nextInt();
int first = 1;
int second = 1;
int temp;
for (int i = 3; i <= num; i++) {
temp = second;//先把变量second保存起来
second = first + second;
first = temp;
}
System.out.println(second);
}
题解
import java.util.Scanner;
public class Main {
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
int num = in.nextInt();
int first = 1;
int second = 1;
int temp;
for (int i = 3; i <= num; i++) {
temp = second;//先把变量second保存起来
second = first + second;
first = temp;
}
System.out.println(second);
}
}
复杂度
时间on
空间o1
📃结语
兄弟们,一起来刷题👉嘎嘎的写题