# 31. Next Permutation

## 1.問題

![](/files/-LO7IJMszwuvXPmbAt6X)

## 2.想法 <a href="#id-2-xiang-fa" id="id-2-xiang-fa"></a>

* 提問
  * 題意: 得到下一個更大的排序,  但盡可能較小
* function header, parameter
* test input
* 說明想法
  * 由於最大的排序是descending, 因此必須要找出從最高位起第一個ascending的位數, 並從此位數的右方中挑出大於該位數又最接近該位數的數值swap, 並且作ascending排序
* 測試計算複雜度

## **3.程式碼** <a href="#id-3-cheng-shi" id="id-3-cheng-shi"></a>

```
class Solution {
public:
    void nextPermutation(vector<int>& nums) {
        int index = nums.size() - 1;
        while (index >0 &&
            nums[index] >= nums[index - 1]) {
            index--;
        }
        if (index == 0) {
            sort(nums.begin(), nums.end());
            return;
        }
        
        int minVal = INT_MAX, minIndex = 0;
        for (int i = nums.size() - 1; i >= index -1; i--) {
            if (nums[i] > nums[index - 1] &&
                minVal > nums[i] ){
                minVal = nums[i];
                minIndex = i;
            }
        }
        
        int tmp = nums[index - 1];
        nums[index - 1] = nums[minIndex];
        nums[minIndex] = tmp;
        
        sort(nums.begin() + index, nums.end());
    }
};
```


---

# Agent Instructions: Querying This Documentation

If you need additional information that is not directly available in this page, you can query the documentation dynamically by asking a question.

Perform an HTTP GET request on the current page URL with the `ask` query parameter:

```
GET https://jenhsuan.gitbook.io/algorithm/leetcode/31.-next-permutation.md?ask=<question>
```

The question should be specific, self-contained, and written in natural language.
The response will contain a direct answer to the question and relevant excerpts and sources from the documentation.

Use this mechanism when the answer is not explicitly present in the current page, you need clarification or additional context, or you want to retrieve related documentation sections.
