Re: [討論] 令人印象深刻的遞迴問題?

看板C_and_CPP作者 (如雲如風的人生)時間13年前 (2011/04/02 12:52), 編輯推噓2(2010)
留言12則, 2人參與, 最新討論串5/9 (看更多)
咦...題目不是要求用遞迴嗎? 原po的作法看不太懂,貼出比較直觀的寫法(就是把迴圈轉換成遞迴orz) void recursion(double* first, double* last, double* best_buy, double* best_sell) { if (first != last) { double max_profit; double buy_price; recursion(first + 1, last, best_buy, best_sell); max_profit = *best_sell - *best_buy; buy_price = *first; while (++first != last) { double sell_price = *first; double pred_profit = sell_price - buy_price; if (max_profit < pred_profit) { *best_buy = buy_price; *best_sell = sell_price; max_profit = pred_profit; } } } else { *best_buy = 0; *best_sell = 0; } } int main() { double price[] = {55.39, 109.23, 48.29, 81.59, 81.58, 105.53, 94.45, 12.24}; double best_buy, best_sell; recursion( price, price + sizeof(price) / sizeof(price[0]), &best_buy, &best_sell); printf("best buy:\t%f\nbest sell:\t%f\nmax profit:\t%f\n", best_buy, best_sell, best_sell - best_buy); return 0; } -- ※ 發信站: 批踢踢實業坊(ptt.cc) ◆ From: 123.204.92.148

04/02 18:14, , 1F
您好,關於我貼的遞迴作法,在此補充程式碼的文字說明:
04/02 18:14, 1F

04/02 18:14, , 2F
04/02 18:14, 2F

04/02 18:37, , 3F
所以是divide&conquer囉?我頭腦簡單就直接用暴力法了XDDD
04/02 18:37, 3F

04/02 18:40, , 4F
這個遞迴做法是思路比較特別,也是別人給答案我才知道的
04/02 18:40, 4F

04/02 18:40, , 5F
遞迴多多少少都有分而治之,把問題縮小的理念在
04/02 18:40, 5F

04/03 22:44, , 6F
補充一下,將recursion(first + 1, last, best_buy...改成
04/03 22:44, 6F

04/03 22:44, , 7F
double *next = first + 1;
04/03 22:44, 7F

04/03 22:44, , 8F
for (; next != last; ++next)
04/03 22:44, 8F

04/03 22:44, , 9F
if (*next < *first)
04/03 22:44, 9F

04/03 22:45, , 10F
break;
04/03 22:45, 10F

04/03 22:45, , 11F
recursion(next, last, best_buy, best_sell);
04/03 22:45, 11F

04/03 22:48, , 12F
可以減少不必要的遞迴,除非遇到worst case否則可以快一點
04/03 22:48, 12F
文章代碼(AID): #1DbgkJpD (C_and_CPP)
討論串 (同標題文章)
文章代碼(AID): #1DbgkJpD (C_and_CPP)