diff --git "a/\347\256\227\346\263\225\346\200\235\347\273\264\347\263\273\345\210\227/\347\203\247\351\245\274\346\216\222\345\272\217.md" "b/\347\256\227\346\263\225\346\200\235\347\273\264\347\263\273\345\210\227/\347\203\247\351\245\274\346\216\222\345\272\217.md" index 79d363fb43181ffd6a9247c20aafc51d5e78cd00..f910b44fa20ec5881d4fc1fa386139d6ad531013 100644 --- "a/\347\256\227\346\263\225\346\200\235\347\273\264\347\263\273\345\210\227/\347\203\247\351\245\274\346\216\222\345\272\217.md" +++ "b/\347\256\227\346\263\225\346\200\235\347\273\264\347\263\273\345\210\227/\347\203\247\351\245\274\346\216\222\345\272\217.md" @@ -123,6 +123,42 @@ void reverse(int[] arr, int i, int j) { ![labuladong](../pictures/labuladong.jpg) +[AkiJoey](https://github.com/AkiJoey) 提供 C++ 解法代码: +```c++ +class Solution { +public: + vector pancakeSort(vector& A) { + sort(A, A.size()); + return res; + } +private: + vector res; + void sort(vector& arr, int n) { + // base case + if (n == 1) + return; + + // 寻找最大饼的索引 + int max = 0, index = 0; + for(int i = 0;i < n;i++) + if (arr[i] > max) { + max = arr[i]; + index = i; + } + + // 第一次翻转,将最大饼翻到最上面 + reverse(arr.begin(), arr.begin() + index + 1); + res.emplace_back(index + 1); + + // 第二次翻转,将最大饼翻到最下面 + reverse(arr.begin(), arr.begin() + n); + res.emplace_back(n); + + // 递归调用 + sort(arr, n - 1); + } +}; +``` [上一篇:拆解复杂问题:实现计算器](../数据结构系列/实现计算器.md)