找到前N个自然数的好排列 C++

找到前N个自然数的好排列 C++

在这个问题中,我们有一个整数值N。我们的任务是找到前N个自然数的好排列。

排列是对一组对象的全部或部分进行安排,考虑到排列的顺序。

好排列是一个排列,其中$1leqslant{i}leqslant{N}$并满足以下条件:

$P_{pi}:=:i$

$P_{p!}:=:i$

让我们举一个例子来理解这个问题,

Input : N = 1
Output : -1

登录后复制

Solution Approach

A simple solution to the problem is by finding permutations p such that pi = i.

Then we will reconsider the equation to satisfy pi != i. So, for a value x such that $2x leqslant x$, we have p2x - 1 and p2k. Now, we have an equation that satisfies the permutation equation for n. Here, the solution for the equation.

Example

Program to illustrate the working of our solution

#include
using namespace std;
void printGoodPermutation(int n) {
if (n % 2 != 0)
cout