查找前 N 个自然数的良好排列 C++
在这个问题中,我们有一个整数 N。我们的任务是查找前 N 个自然数的良好排列。
排列是指对集合中的所有或部分对象进行排列,并考虑排列的顺序。
良好排列是一种排列,其中1⩽i⩽N,并且遵循:
Ppi=i
Pp!=i
让我们来看一个例子来理解这个问题:
Input : N = 1 Output : -1
解决方案方法
解决这个问题的一个简单方法是找到满足 pi = i 的排列 p。
然后我们将重新考虑方程以满足 pi != i。因此,对于满足2x⩽x的值 x,我们有 p2x - 1 和 p2k。现在,我们有一个满足 n 的排列方程的方程。这里的方程解是……
示例
程序说明了我们解决方案的工作原理
#include <iostream> using namespace std; void printGoodPermutation(int n) { if (n % 2 != 0) cout<<-1; else for (int i = 1; i <= n / 2; i++) cout<<(2*i)<<"\t"<<((2*i) - 1)<<"\t"; } int main() { int n = 4; cout<<"Good Permutation of first N natural Numbers : \n"; printGoodPermutation(n); return 0; }
Explore our latest online courses and learn new skills at your own pace. Enroll and become a certified expert to boost your career.
输出
Good Permutation of first N natural Numbers : 2 1 4 3
广告