[LeetCode][Java] 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, do not allocate 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

题意:

开始就没读懂题,后来终于找到一个说明白的解释。

* 首先要明白:什么是next permutation. 简单点说,如果输入的数字有大小的话,那么 next permutation就是下一个大于它并"最接近"它的全排列.

* 比如123, 下一个使用 这三个数字的排列就是132(213, 312虽然也是全排列,但是都比132大)

* 如果这个全排列已经是最大的了(全部升序排列),那么它的next permutation就来一个 "头尾想接"(就是最小的数字):

* 比如321的排列已经是最大的了, 所以next permutation 就是把321完全反转成最小的123

算法分析:

参考:http://harrifeng.github.io/algo/leetcode/next-permutation.html

实现一般分下面四个步骤(对应图):

  1. 从后往前找,找到第一个array[i] < array[i+1]的地方, 这个地方是整个字符串 最晚的"升序"的地方,而且在数字尾端,更改的话最容易做到"最接近".通过从后往前 逐个比较,我们发现8这个数字是一个分界线.8后面的数字都是降序的(也就是最大的了)
  2. 我们如果直接把6和8一交换,肯定也会产生一个permutation,但是不是"最接近的",怎样 找到"最接近"的呢,就要从1到8后面这端寻找一个比6大,并且和6差距最小的(也就是从 后往前第一个比6大的数字),我们找到了是7
  3. 7作为最佳选择,和6进行调换. 7后面肯定还是decrease的状态(也就是能组成的最大值)
  4. 为了达到"最接近",我们在6变成7的情况下已经增长很多了.所以我们要把7后面的一系列 decrease的数组反转(也就是能组成的最小值)

AC代码:

<span style="font-size:12px;">public class Solution
{
	 public static void nextPermutation(int[] num)
	 {
        if (num.length <= 1)
            return;

        for (int i = num.length - 2; i >= 0; i--)
        {
            if (num[i] < num[i+1])
            {
                int j;
                for (j = num.length - 1; j >= i; j--)
                {
                    if (num[i] < num[j]) //找到比num[i]大但是和其差距最小的一个
                        break;
                }
                // swap the two numbres
	            int temp = num[i];
	            num[i] = num[j];
	            num[j] = temp;
	            // sort the rest of arrays after the swap point
	            Arrays.sort(num, i+1, num.length);
	            return;
            }
        }
	    // if the whole array is all in descending order(can't become bigger),
	    // you have to reverse the array
	    for (int i = 0; i < num.length / 2; i++)
	    {
	        int temp = num[i];
	        num[i] = num[num.length - i - 1];
	        num[num.length - i - 1] = temp;
	    }
	    return;
	}
}</span>

版权声明:本文为博主原创文章,转载注明出处

时间: 2024-11-02 21:37:52

[LeetCode][Java] Next Permutation的相关文章

[LeetCode] 031. Next Permutation (Medium) (C++/Python)

索引:[LeetCode] Leetcode 题解索引 (C++/Java/Python/Sql) Github: https://github.com/illuz/leetcode 031. Next Permutation (Medium) 链接: 题目:https://oj.leetcode.com/problems/next-permutation/ 代码(github):https://github.com/illuz/leetcode 题意: 求一个序列的下一个排列. 分析: 可以用

Spiral Matrix leetcode java

题目: Given a matrix of m x n elements (m rows, n columns), return all elements of the matrix in spiral order. For example, Given the following matrix: [ [ 1, 2, 3 ], [ 4, 5, 6 ], [ 7, 8, 9 ] ] You should return [1,2,3,6,9,8,7,4,5]. 题解: 这道题是实现题. 考虑2个初始

Pascal&#39;s Triangle II Leetcode java

题目: Given an index k, return the kth row of the Pascal's triangle. For example, given k = 3, Return [1,3,3,1]. Note: Could you optimize your algorithm to use only O(k) extra space? 题解: 为了达到O(k)的空间复杂度要求,那么就要从右向左生成结果.相当于你提前把上一行的计算出来,当前行就可以用上一次计算出的结果计算了

Spiral Matrix II leetcode java

题目: Given an integer n, generate a square matrix filled with elements from 1 to n2 in spiral order. For example, Given n = 3, You should return the following matrix: [ [ 1, 2, 3 ], [ 8, 9, 4 ], [ 7, 6, 5 ] ] 题解:这道题跟Spiral Matrix想法也是类似的,就是依照矩阵从外圈到内圈建立

Pascal&#39;s Triangle leetcode java(杨辉三角)

题目: Given numRows, generate the first numRows of Pascal's triangle. For example, given numRows = 5, Return [ [1], [1,1], [1,2,1], [1,3,3,1], [1,4,6,4,1] ] 题解:既然讲到了Pascal‘s Triangle,即杨辉三角.那么就先去Wikipedia上面复习一下杨辉三角吧:”杨辉三角形,又称賈憲三角形.帕斯卡三角形.海亚姆三角形,是二项式係數在的

Triangle leetcode java

题目: Given a triangle, find the minimum path sum from top to bottom. Each step you may move to adjacent numbers on the row below. For example, given the following triangle [ [2], [3,4], [6,5,7], [4,1,8,3] ] The minimum path sum from top to bottom is 1

[Leetcode][JAVA] Pascal&#39;s Triangle I, II

Pascal's Triangle: Given numRows, generate the first numRows of Pascal's triangle. For example, given numRows = 5,Return [ [1], [1,1], [1,2,1], [1,3,3,1], [1,4,6,4,1] ] 已知行数生成帕斯卡三角.实际上只要有第i层,那么就能生成第i+1层.每次新生成的层加入最终集合中即可. 1 public List<List<Integer&g

Permutations II leetcode java

题目: Given a collection of numbers that might contain duplicates, return all possible unique permutations. For example, [1,1,2] have the following unique permutations: [1,1,2], [1,2,1], and [2,1,1]. 题解: 这道题跟Permutaitons没啥大的区别,就是结果去重. 我之前也有写过去重的两个方法: 一

Word Ladder leetcode java

题目: Given two words (start and end), and a dictionary, find the length of shortest transformation sequence from start to end, such that: Only one letter can be changed at a time Each intermediate word must exist in the dictionary For example, Given: