LeetCode31 下一个排列
发布日期:2021-05-14 23:49:55 浏览次数:19 分类:精选文章

本文共 2536 字,大约阅读时间需要 8 分钟。

���������������������������������Next Permutation������������������������������������������������:

������1������������������

������������������������������������������������������������������������������������������������������sub2���������������������3,2,1������������������������������sub2���������������������������������������������������������������������������������������������������������

������2���������������������������������

���������������������������������������sub2������������������������������������������������������������������������������������������������������������������������������������3,2,1���������������1,2,3���

������3���������������������������

���������sub2������������������������������������nums[sub2]������������������������������������������sub1���������������������������������������������������1,2,3������sub2=1���sub1=2������������������1,3,2���

������4������������������������

������������������������sub1������������������������������������������������������������������������������������������������������������������������������������1,3,2���������������������������������������������������������������

���������Python������������������������������

def next_permutation(nums):
n = len(nums)
sub2 = n - 2 # ������������sub2���������������������������������
# Step 1: Find the first index from the end where nums[sub2] < nums[sub2 + 1]
for i in range(n-2, -1, -1):
if nums[i] < nums[i + 1]:
sub2 = i
break
else:
# If no such index, return the smallest permutation
nums.reverse()
return
# Step 2: Find the largest index sub1 greater than sub2 such that nums[sub1] > nums[sub2]
sub1 = n - 1
for i in range(n-1, sub2, -1):
if nums[i] > nums[sub2]:
sub1 = i
break
# Step 3: Swap the values at sub1 and sub2
nums[sub1], nums[sub2] = nums[sub2], nums[sub1]
# Step 4: Reverse the subarray from sub1+1 to end
nums[sub1 + 1:] = reversed(nums[sub1 + 1:])
return

���������������

  • Step 1���������������������������������������������������������������������������������������������sub2���
  • Step 2������������������sub2���������������������������������������������������������
  • Step 3������sub2������������������������nums[sub2]������������������������������
  • Step 4������������sub1+1������������������������������������������������������������������

������������������������������������������������������������������������������������������������������������������������

上一篇:LeetCode62/63/64 不同路径I/II/最小路径和
下一篇:LeetCode17 电话号码的字母组合

发表评论

最新留言

路过,博主的博客真漂亮。。
[***.116.15.85]2025年04月22日 06时23分29秒