n = 0 时,队列为空,可以认为只有一种;
n = 1 时,队列:5 ,10 共有1种;
n = 2 时 ,队列: 5, 10,5,10
5,5,10,10 共有两种
n = 3时, 队列:5,5,5,10,10,10
5,5,10,5,10,10
5,5,10,10,5,10
5,10,5,5,10,10
5,10,5,10,5,10 共有5种;
我门可以认为符合卡特兰数,1,1,2,5,14,42.。。。
接下来时验证,小编在做n=3的情况是,发现可以认为有两个容器,一个全部都放5元的票,另一个全部放10元的票,这里遵循三个规则:
1、当5元容器和10元容器全部为空时,输出序列
2、5元容器不为空时,5元出容器
3、10元容器不为空并且10元容器的个数必须大于5元容器的个数(也就是当10元容器的个数和5元容器的个数相等时,10不能出容器)
//
// main.cpp
// CSDN.卡特兰数:售票序列问题
//
// Created by Mr Gao on 2018/4/12.
// Copyright © 2018年 Mr Gao. All rights reserved.
//
#include
#include
#include
using namespace std;
void genAns(int left, int right, string path, vector<string> &ans){
if(left == 0 && right == 0){ //规则一
path.pop_back();
ans.push_back(path);
}
if(left != 0) //规则二
genAns(left - 1, right, path + "5-", ans);
if(right != 0 && left < right) //规则三
genAns(left, right - 1, path + "10-", ans);
}
int main(int argc, const char * argv[]) {
// insert code here...
int n;
while(cin>>n){
string path;
vector<string> ans;
genAns(n, n, path, ans);
for(int i = 0; i < ans.size(); i++)
std::cout << ans[i] <<endl;
cout<<"count: "<
}
return 0;
}
代码输出:
1
5-10
count: 1
2
5-5-10-10
5-10-5-10
count: 2
3
5-5-5-10-10-10
5-5-10-5-10-10
5-5-10-10-5-10
5-10-5-5-10-10
5-10-5-10-5-10
count: 5
4
5-5-5-5-10-10-10-10
5-5-5-10-5-10-10-10
5-5-5-10-10-5-10-10
5-5-5-10-10-10-5-10
5-5-10-5-5-10-10-10
5-5-10-5-10-5-10-10
5-5-10-5-10-10-5-10
5-5-10-10-5-5-10-10
5-5-10-10-5-10-5-10
5-10-5-5-5-10-10-10
5-10-5-5-10-5-10-10
5-10-5-5-10-10-5-10
5-10-5-10-5-5-10-10
5-10-5-10-5-10-5-10
count: 14
根据程序输出结果可以验证是符合卡特兰数:
根据卡特兰数的公式:C(2n, n) / (n+1) = (2n)! / ( n! * (n+1)! )
//
// main.cpp
// CSDN. 卡特兰数
//
// Created by Mr Gao on 2018/4/12.
// Copyright © 2018年 Mr Gao. All rights reserved.
//
#include
using namespace std;
int main(int argc, const char * argv[]) {
// insert code here...
int n;
while(cin >> n){
if(n == 1 || n == 0)
cout<<1<<endl;
double ans = 1;
for(int i = 1; i <= n; i++){
ans = ans * (n + i) / i;
}
cout<< ans / (n+1) << endl;
}
return 0;
}
结果展示:
0
result:1
1
result:1
2
result:2
3
result:5
4
result:14
5
result:42
6
result:132
7
result:429
8
result:1430
小编的第一篇博客,写了好久,希望对大家有帮助。