【发布时间】: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