```
def nextPermutation(self, nums):
i = l = len(nums)-1
while i > 0:
# find the right most pair where nums[i] > nums[i-1]
if nums[i] > nums[i-1]:
tmp = 0
for j in xrange(l, i-1, -1):
if nums[j] > nums[i-1]:
tmp = j
break
# exchange nums[i-1] and the right most element which larger than nums[i-1]
nums[i-1], nums[tmp] = nums[tmp], nums[i-1]
# reverse from i to the end
for j in xrange(i, 1+i+(l-i)/2):
nums[j], nums[l+i-j] = nums[l+i-j], nums[j]
break
i -= 1
# if nums are in descending order
if i == 0:
nums.reverse()
```