Conversation
|
|
||
|
|
||
| - pythonでメモ化再帰をデコレータを書いている方がいらっしゃるので、自分もトライしてみる | ||
| - 高階関数("関数を受け取って関数を返す"関数)なのか、C++には なさそうだ |
There was a problem hiding this comment.
C++ は operator () の定義されたクラスを作る方法で同等のことができます。
関数オブジェクトで調べてください。
There was a problem hiding this comment.
コメントありがとうございます。()演算子をオーバーライドすることで、関数のようにコードが見えるオブジェクトを作ることができ、この関数オブジェクトを受け取る関数クラスを作ることで、高階関数を再現できると理解しました。
以下足し算の関数に引数のログを加える高階関数をchatgptに相談しながら作成しました
#include <iostream>
// 元の関数オブジェクト(加算)
class Func {
public:
int operator()(int a, int b) {
return a + b;
}
};
// デコレータクラス(ログを追加)
class LoggingDecorator {
public:
LoggingDecorator(Func add) : f_(add) {}
int operator()(int a, int b) {
std::cout << "引数: " << a << ", " << b << endl;
int result = f_(a, b);
std::cout << "結果: " << result << endl;
return result;
}
private:
Func f_; // Func型の関数オブジェクトを保持
};
int main() {
Func add; // 元の関数オブジェクト
LoggingDecorator decorated_func(add); // デコレータでラップ
int sum = decorated_func(3, 5); // ログ付きで実行
return 0;
}ここから再帰関数をメモ化する応用はまだ理解が追いついておらず難しかったので、2周目の宿題にしようと思います
| house_to_gain[i - 2] + nums[i]); | ||
| } | ||
| int candidate_1 = std::max(house_to_gain[num_houses - 1], | ||
| house_to_gain[num_houses - 2]); |
There was a problem hiding this comment.
DPは「あるindexまでの得られる利得の最大値」のため、house_to_gain.back()がそのまま最大値となり、ここのstd::maxは不要でした
| house_to_gain[i - 2] + nums[i]); | ||
| } | ||
| return std::max(house_to_gain[num_houses - 1], | ||
| house_to_gain[num_houses - 2]); |
There was a problem hiding this comment.
上記のコメント同様、DP配列の場合、この比較は不要でした
以下の実装でも同様です
| 6分,6分,5分で3回Accept | ||
|
|
||
| #### 2周目の宿題 | ||
| - lru_cacheを実装する(pythonでも) |
There was a problem hiding this comment.
宿題に追加
pairにしてメモ化しなくても良くする方法
https://discord.com/channels/1084280443945353267/1206101582861697046/1229120056248766627
| if (num_houses == 0) { | ||
| return 0; | ||
| } | ||
| if (num_houses <= 2) { |
|
|
||
| private: | ||
| int max_gain_in_range(const std::vector<int>& nums, int start, int end) { | ||
| std::vector<int> house_to_gain(nums.size()); |
There was a problem hiding this comment.
サイズは nums.size()-1 か end-start+1 の方がいいのではないでしょうか?
This Problem
House Robber II
Next Problem
Best Time to Buy and Sell Stock