我已经建立了递归函数来计算Pascal的三角形值.
有没有办法优化它?
关于Pascal三角形的简短提醒:C(n,k)= C(n-1,k-1)+ C(n-1,k)我的代码是:
int Pascal(int n, int k) {
if (k == 0) return 1;
if (n == 0) return 0;
return Pascal(n - 1, k - 1) + Pascal(n - 1, k);
}
Run Code Online (Sandbox Code Playgroud)
我看到的低效率是它存储了两次值.例:C(6,2)= C(5,1)+ C(5,2)C(6,2)= C(4,0)+ C(4,1)+ C(4,1)+ C(4,2)它将调用C(4,1)两次
知道如何优化这个功能吗?
谢谢
在我的cs106b书中,我们使用表达式"foreach"来浏览Map中的单词列表.我实施了这些代码,并将我的头撞在墙上,面对神秘的错误.这是代码:
void DisplayWordCounts(Map<int> & wordsCount) {
foreach (string word in wordsCount) {
cout << left << setw(15) << word << right << setw(5)
<< wordsCount[word] << endl;
}
}
Run Code Online (Sandbox Code Playgroud)
在以"foreach"开头的行上我得到以下错误:lesson4-macbeth/life.cpp:58:错误:在'word'之前预期的primary-expression lesson-macbeth/life.cpp:58:错误:'foreach'是未在此范围内声明lesson4-macbeth/life.cpp:58:错误:预期`;' 在'{'之前
我想foreach不被认可.在这种情况下,我如何查看Map类中的项目列表?
如果我写完整路径(full-path/roots.txt),文件将打开.如果我只写文件名(roots.txt),文件无法打开
然而,roots.txt与main.cpp位于同一个文件夹中.我应该在XCode上查看任何设置吗?
这是代码:
string line;
ifstream infile;
infile.clear();
// infile.open("roots.txt");
infile.open("/Users/programming/C++/roots/roots.txt");
if (infile.fail()) cout << "could not open the file: " << strerror(errno);
getline(infile, line);
cout << line;
Run Code Online (Sandbox Code Playgroud)