【问题标题】:Next_Permutation algorithmNext_Permutation 算法
【发布时间】:2019-08-24 07:05:19
【问题描述】:

我正在尝试编写一个算法来获取给定整数数组的下一个排列。 我当前的代码仅适用于少数输入。 因此,我需要帮助找出哪里出了问题。

预期输出与输入仅在最后三个元素不同。所以我检查了最后三个元素的算法实现。

void Solution::nextPermutation(vector<int> &A) {
    int j, i;
    for (i = A.size() - 1; i > 0; i--) {
        // loop to find i such that A[i-1] < A[i];

        if (A[i - 1] < A[i]) {
            j = i;
            break;
        }
    }

    if (i == 0)
        sort(A.begin(), A.end());
    // to give the lowest order if next_permutation is not possible

    if (i > 0) {
        // if next permutation is possible

        // to swap last element and element at j-1 th index

        if (j == A.size() - 1)
            swap(A[j-1], A[A.size() - 1]);
        else {
            for(int k = A.size() - 1; k >= j; k--) {
                if (A[k] > A[j-1]) {
                    swap(A[k], A[j- 1]);
                    break;
                }
            }
        }

        //to sort the elements after j-1 th index
        sort(A.begin()+j,A.end());
    }

输入:

[444, 994,701, 319, 695, 52]

预期输出:

[444,994,701,695,52,319]

实际输出:

[444,994,701,52,319,695]

【问题讨论】:

  • 括号不平衡。你确定可以编译吗?
  • 是的,它工作得很好

标签: c++ c++11 permutation


【解决方案1】:

如果您在 j - 1 之后对向量进行排序,则不需要交换。

// Example program
#include <iostream>
#include <vector>
#include <bits/stdc++.h>
using namespace std;

void nextPermutation(vector<int> &A) {
    int j,i;
    for(i=A.size()-1;i>0;i--){//loop to find i such that A[i-1]<A[i];
        if(A[i-1]<A[i]){j=i;break;}
    }
    if(i==0){sort(A.begin(),A.end());}
     /*to give the lowest order if  next_permutation 
    is not possible*/


    if(i>0){
        //if next permutation is possible
        //to swap last element and element at j-1 th index
        // swap(A[j-1],A[A.size()-1]);
        //to sort the elements after j-1 th index
        std::sort(A.begin()+j,A.end());
    }
}

int main()
{
    std::vector<int> v= {444, 994,701, 319, 695, 52};
    nextPermutation(v);
    for (int i = 0; i< v.size(); i++) {
        std:: cout << v[i] << "\n";
    }
}

另一个建议:您可以完全避免排序。求 [j+1, ..., n] 中的 k 使得 v[k] 是最小元素 > v[j],然后将向量 v[j ... k-1] 顺时针旋转一个单位(第一个元素到最后)。

【讨论】:

  • 您的方法似乎是正确的,但您的代码输出与下一个排列的 stl 获得的输出不匹配。
猜你喜欢
  • 2016-08-04
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2012-07-14
  • 2015-09-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多