Skip to content

Instantly share code, notes, and snippets.

@yusuketanabe
Last active February 7, 2022 03:35
Show Gist options
  • Save yusuketanabe/2d818875353a37a6923fe3f288967e87 to your computer and use it in GitHub Desktop.
Save yusuketanabe/2d818875353a37a6923fe3f288967e87 to your computer and use it in GitHub Desktop.
Recursive function memo
#include <iostream>
#include <vector>
// dataのi番目以降の要素を逆順にした配列を返す
std::vector<int> reverse_array_from_i(std::vector<int> &data, int i) {
// Base
if (i == data.size()) {
std::vector<int> empty_array(0); // 要素数0の配列。0なので出力されない。試しに1とか入れてみて。出力されるから。
return empty_array;
/*
この例ならばi==4まで繰り返し再帰関数を呼び出し、Basecaseまで達したらempty_arrayを出力して
再帰呼び出しを終了し、その後の処理(tmp.push_back(data.at(i)); -> return tmp;)を実行する。
*/
}
// Recursive
std::vector<int> tmp = reverse_array_from_i(data, i + 1); // dataのi+1番目以降の要素を逆順にした配列を得るための再帰呼び出し
tmp.push_back(data.at(i)); // 与えられた配列の末尾に達したら(i番目)順に、新しい配列の末尾にdataのi番目の要素を追加
return tmp;
}
// 配列を逆順にしたものを返す
std::vector<int> reverse_array(std::vector<int> &data) {
return reverse_array_from_i(data, 0);
}
int main() {
std::vector<int> a = {1, 2, 3, 4, 5};
std::vector<int> b = reverse_array(a);
for (int i = 0; i < b.size(); i++) {
std::cout << b.at(i) << std::endl;
}
}
/* output
5
4
3
2
1
*/
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment