题解(C++ PYTHON JAVA)
2024-03-16 18:54:24
发布于:北京
12阅读
0回复
0点赞
这道题是个基本题,十分的简单。
所以,我们要用3种语言去做,巩固基本知识。
先来了解基本语法:
传送门
C++实现
#include<bits/stdc++.h>
using namespace std;
long long s[105];
int main() {
s[1]=1;
s[2]=2;
int n;
cin>>n;
s[3]=4;
for(int i=4;i<=n;i++){
s[i]=s[i-1]+s[i-2]+s[i-3];
}
cout<<s[n];
return 0;
}
PY实现:
# Initialize the s array with initial values
s = [0] * 105
s[1] = 1
s[2] = 2
s[3] = 4
# Take input for n
n = int(input())
# Calculate the values of s from 4 to n
for i in range(4, n + 1):
s[i] = s[i - 1] + s[i - 2] + s[i - 3]
# Print the value of s at index n
print(s[n])
java实现:
import java.util.Scanner;
public class Main {
public static void main(String[] args) {
long[] s = new long[105];
s[1] = 1;
s[2] = 2;
s[3] = 4;
Scanner scanner = new Scanner(System.in);
int n = scanner.nextInt();
for (int i = 4; i <= n; i++) {
s[i] = s[i - 1] + s[i - 2] + s[i - 3];
}
System.out.println(s[n]);
}
}
这里空空如也
有帮助,赞一个