dinner_shuffles方法应该返回n个晚餐客人的所有可能的安排,作为字符串的向量。使用的名称应该是构造函数中指定的首n个名称。
字符串的末端代表圆桌的相邻端椅。
宴会安排的顺序没有具体说明。
下面是一个简单的例子。如果晚餐客人是abcde,那么dinner_shuffles(3)的结果将是:
abc acb bac bca 驾驶室 cba
**更新:我发现Fibonacci序列对于组合数如下: F(n) = F(n-1) + F(n-2) - 2。我是c++的新手,我不确定如何用字母表示来可视化这个序列。
发布于 2018-04-02 07:25:37
即使知道定义这种递归关系的方程式,也会很有帮助,谢谢
这个方程类似于这
这个问题是一样的,只要看看是否有1人站着,便只剩下一个选择,否则便可以安排下一个座位。
如果这的简化代码仍然没有意义的话,试着在这里进行一步。
否则,请查看此解决方案:
#include <iostream>
#include <vector>
using namespace std;
vector<string> arrangements;
class Table
{
public:
string seated = "";
string notSeated = "";
Table(string n);
vector<string> dinner_shuffles(int n);
};
Table::Table(string n)
{
seated = "";
notSeated = n;
}
vector<string> Table::dinner_shuffles(int n)
{
//The names used should be the first n names as designated in the constructor.
notSeated = notSeated.substr(0, n);
if (notSeated.length() == 1)
{
arrangements.push_back(seated+notSeated);
}
for (int i = 0; i < notSeated.length(); i++)
{
Table newArrangement(notSeated.substr(0,i) + notSeated.substr(i+1, notSeated.length()));
newArrangement.seated = seated + notSeated[i];
newArrangement.dinner_shuffles(n);
}
//return all possible arrangements of n dinner guests as a vector of strings.
return arrangements;
}
int main()
{
//dinner guest names are fed in as a string
string notSeated = "abcde";
Table table(notSeated);
vector<string> vals = table.dinner_shuffles(3);
//abc, acb, bac, bca, cab, cba
for (int i = 0; i < vals.size(); i++){
cout << vals[i] << endl;
}
return 1;
}https://stackoverflow.com/questions/49602580
复制相似问题