> For the complete documentation index, see [llms.txt](https://jimmylin1991.gitbook.io/practice-of-algorithm-problems/llms.txt). Markdown versions of documentation pages are available by appending `.md` to page URLs; this page is available as [Markdown](https://jimmylin1991.gitbook.io/practice-of-algorithm-problems/array/31.-next-permutation.md).

# 31. Next Permutation

Implement **next permutation**, which rearranges numbers into the lexicographically next greater permutation of numbers.

If such arrangement is not possible, it must rearrange it as the lowest possible order (ie, sorted in ascending order).

The replacement must be [**in-place**](http://en.wikipedia.org/wiki/In-place_algorithm) and use only constant extra memory.

Here are some examples. Inputs are in the left-hand column and its corresponding outputs are in the right-hand column.

`1,2,3` → `1,3,2`\
`3,2,1` → `1,2,3`\
`1,1,5` → `1,5,1`

{% hint style="info" %}
先從數列的尾巴開始向前搜尋第一個遞減的數字(index i)，然後再從尾巴搜尋第一個大於前面搜尋到的那個數字(index j)，兩者互換之後將第一個搜尋到的數字後方的數字反轉。\
e.g. \[1, 2, 5, 4, 3, 1]\
從後向前搜尋第一個遞減的數字是2(i = 1)，從後向前搜尋第一個比2大的數字是3(j = 4)，互換之後變成\[1, 3, 5, 4, 2, 1]，再把index = 1之後的數列反轉，從index = 2開始反轉，最後變成\[1, 3, 1, 2, 4, 5]。
{% endhint %}

```cpp
void nextPermutation(vector<int>& nums) { // time: O(n); space: O(1)
    int n = nums.size();
    for (int i = n - 2; i >= 0; --i) {
        if (nums[i] < nums[i + 1]) {
            int j;
            for (j = n - 1; j > i; --j) {
                if (nums[j] > nums[i]) break;
            }
            swap(nums[i], nums[j]);
            reverse(nums.begin() + i + 1, nums.end());
            return;
        }
    }
    reverse(nums.begin(), nums.end());
}
```

```cpp
void nextPermutation(vector<int>& nums) { // time: O(n); space: O(1)
    int n = nums.size(), i = n - 2, j = n - 1;
    // Search from the end to find the first element which is not ascending
    while (i >= 0 && nums[i] >= nums[i + 1]) --i;
    if (i >= 0) {
        // Search from the end to find the first element which is larger than nums[i]
        while (nums[i] >= nums[j]) --j;
        swap(nums[i], nums[j]);
    }
    reverse(nums.begin() + i + 1, nums.end());
}
```


---

# Agent Instructions
This documentation is published with GitBook. GitBook is the documentation platform designed so that both humans and AI agents can read, navigate, and reason over technical content effectively. Learn more at gitbook.com.

## 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, and the optional `goal` query parameter:

```
GET https://jimmylin1991.gitbook.io/practice-of-algorithm-problems/array/31.-next-permutation.md?ask=<question>&goal=<endgoal>
```

`ask` is the immediate question: it should be specific, self-contained, and written in natural language.
`goal` is optional and describes the broader end goal you are ultimately trying to accomplish on behalf of the user. GitBook uses it to tailor the answer towards what is most useful for that goal.

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.
