prev_permutation_cycle与next_permutation_cycle
2017-09-03 09:00
393 查看
下一个排列与上一个排列的实现:
例如:1234的下一个排列为1243,在下一个排列为1324因此可以设置两个相邻的指针i,ii,指针从后往前搜索,直到*i <*ii,
这里为i->3; jj->4;然后设置指针j从最后往前搜索,找到第一个大于i的,即*i<*j;这里j->4;交换i与j的元素,然后将ii到最后逆序。
上一个排列的思路为 *i>*ii , *i > *j ,交换i与j,ii后逆序
例如:1234的下一个排列为1243,在下一个排列为1324因此可以设置两个相邻的指针i,ii,指针从后往前搜索,直到*i <*ii,
这里为i->3; jj->4;然后设置指针j从最后往前搜索,找到第一个大于i的,即*i<*j;这里j->4;交换i与j的元素,然后将ii到最后逆序。
上一个排列的思路为 *i>*ii , *i > *j ,交换i与j,ii后逆序
void next_permutation_cycle(int* arr, int n){ if (n < 2){ return; } int right = n - 2, left = n - 1;//right与left写反了。。。。。。 while (1){ if (arr[right] < arr[left]){ int big_right = n - 1; while (!(arr[big_right] > arr[right])){ --big_right; } swap(arr[big_right], arr[right]); reverse(&arr[left], &arr ); break; } if (right == 0){ reverse(&arr[0], &arr ); break;} --right; --left; } } void prev_permutation_cycle(int* arr, int n){ if (n < 2){ return; } int left = n - 2; int right = n - 1; while (1){ if (arr[left] > arr[right]){ int j = n - 1; while (!(arr[left]>arr[j])){ --j; } swap(arr[left], arr[j]); reverse(&arr[right], &arr ); break; } if (left == 0){ reverse(&arr[0], &arr ); break; } --left; --right; } }
相关文章推荐
- STL之生成全排列:next_permutation & prev_permutation
- C++ 求排列函数 next_permutation, prev_permutation
- STL算法:prev_permutation和next_permutation的使用
- next_permutation,prev_permutation
- STL经典算法集锦<六>之排列(next_permutation/prev_permutation)
- STL经典算法集锦之排列(next_permutation/prev_permutation
- C++ 全排列函数 std::next_permutation与std::prev_permutation
- C++ STL next_permutation() & prev_permutation()函数
- 【经典算法】STL之next_permutation be52 和prev_permutation
- next_permutation()函数 和 prev_permutation() 按字典序求全排列
- stl全排列next_permutation()与prev_permutation()函数用法
- C++标准库---排列元素next_permutation()&prev_permutation()
- 全排列函数——next_permutation() & prev_permutation()
- next_permutation和prev_permutation(全排列)
- 全排列函数 next_permutation && prev-permutation
- next-permutation与prev-permutation及递归实现全排列
- stl中的next_permutation和prev_permutation
- next_permutation和prev_permutation
- 黑科技(next_permutation和prev_permutation)
- STL算法:prev_permutation和next_permutation的使用