题目描述
给出正整数 n n n,要求按如下方式构造数列:
- 只有一个数字 n n n 的数列是一个合法的数列。
- 在一个合法的数列的末尾加入一个正整数,但是这个正整数不能超过该数列最后一项的一半,可以得到一个新的合法数列。
请你求出,一共有多少个合法的数列。两个合法数列 a , b a, b a,b 不同当且仅当两数列长度不同或存在一个正整数 i ≤ ∣ a ∣ i \leq |a| i≤∣a∣,使得 a i ≠ b i a_i \neq b_i ai=bi。
输入格式
输入只有一行一个整数,表示 n n n。
输出格式
输出一行一个整数,表示合法的数列个数。
样例 #1
样例输入 #1
6
样例输出 #1
6
提示
样例 1 解释
满足条件的数列为:
- 6 6 6
- 6 , 1 6, 1 6,1
- 6 , 2 6, 2 6,2
- 6 , 3 6, 3 6,3
- 6 , 2 , 1 6, 2, 1 6,2,1
- 6 , 3 , 1 6, 3, 1 6,3,1
数据规模与约定
对于全部的测试点,保证 1 ≤ n ≤ 1 0 3 1 \leq n \leq 10^3 1≤n≤103。
算法思路
这道题很明显适合用递归,把大问题拆成许多子问题,但是为了避免重复的计算导致时间复杂度过大造成的超时,可以采取记忆化搜索,用一个数组(字典)memo记录下以n开头的序列个数,如果在递归的计算中再一次遇到了n,就直接从memo里拿,避免了重复运算,可以有效降低时间复杂度。
python代码
def f(n, memo):
if n == 1:
return 1
if n in memo:
return memo[n]
count = 1
for i in range(1, n):
if n - i <= n / 2:
count += f(n - i, memo)
memo[n] = count
return count
n = int(input())
memo = {}
print(f(n, memo))
C++代码
#include <bits/stdc++.h>
using namespace std;
vector<int> memo(10001, -1);
int f(int n) {
if (n == 1) {
return 1;
}
if (memo[n] != -1) {
return memo[n];
}
int count = 1;
for (int i = 1; i < n; ++i) {
if (n - i <= n / 2) {
count += f(n - i);
}
}
memo[n] = count;
return count;
}
int main() {
int n;
cin >> n;
cout << f(n) << endl;
return 0;
}
更简单的方法
#include<bits/stdc++.h>
using namespace std;
const int N=2005;
int cnt;
void solve(int x){
cnt+=x/2;
for(int i=2;i<=x/2;i++){
solve(i);
}
}
signed main()
{
int n;
cin>>n;
solve(n);
cout<<cnt+1;
return 0;
}