diff --git a/算法思维系列/烧饼排序.md b/算法思维系列/烧饼排序.md index 513cbdc..67604ae 100644 --- a/算法思维系列/烧饼排序.md +++ b/算法思维系列/烧饼排序.md @@ -149,4 +149,41 @@ void reverse(int[] arr, int i, int j) {

-======其他语言代码====== \ No newline at end of file +======其他语言代码====== + +[fengshuu](https://github.com/fengshuu) 提供 Python3 解法代码: +```python +class Solution: + # 记录反转操作序列 + def __init__(self): + self.res = [] + + def pancakeSort(self, arr: List[int]) -> List[int]: + + self.sort(arr, len(arr)) + return self.res + + def sort(self, cakes: List[int], n: int): + # base case + if 1 == n: + return + + # 寻找最大饼的索引 + max_cake_index = cakes[:n].index(n) + + # 下面进行把最大的饼放到最后的两次翻转 + # 如果最后一个饼就是最大的, 就不需要翻转, 直接进行下次递归 + if max_cake_index != n - 1: + # 第一次翻转, 将最大饼翻到最上面 + # 如果第一个饼本来就是最大的, 就不需要第一次翻转. + if max_cake_index != 0: + cakes[:max_cake_index + 1] = cakes[:max_cake_index + 1][::-1] + self.res.append(max_cake_index + 1) + + # 第二次翻转,将最大饼翻到最下面 + cakes[:n] = cakes[:n][::-1] + self.res.append(n) + + # 递归调用 + self.sort(cakes, n - 1) +``` \ No newline at end of file