如何在不使用 C++ 中的数组或函数的情况下查找 N 位数字的所有排列

how to find all permutations of an n digit number without using array or function in c++

本文关键字:查找 情况下 数字 排列 函数 数组 C++      更新时间:2023-10-16

我在使这段代码按照我想要的方式工作时遇到了问题。任务是编写一个程序,该程序打印通过输入的数字 n (1 <= n <= 9( 的数字 1 到 n 排列获得的所有数字。该程序还应打印出有多少个这样的数字。我做了一个 for 循环,它得到了 n 的阶乘,这样我就可以得到排列的数量,我将从 1 到 n 的所有数字组合成一个整数,因为我认为应该有一种方法可以找到排列。所以我的问题是如何找到这些排列?

#include <iostream>
using namespace std;
int main(){
int n;
int j;
int r=0;
int t=1;
double f=1;
cin>>n;
for(int p=1;p<=n-1;p++){
t=t*10;
}
int u=t;
//calculates the factorial of n
for(int o=1;o<=n;o++){
f=f*o;
}
//writes numbers from 1 to n into an integer
for(int d=1;d<=n;d++){
j=d*u;
r=r+j;
u=u/10;
}
}

首先,将数字读入字符串。如果要确保格式正确,可以将其读取为整数,然后将其写入字符串:

int number;
if (!(std::cin >> number)) {
// Failure to read number. Do some diagnostic.
throw std::runtime_error("invalid number");
}
// Number read successfully. Write it to a string.
std::string s = std::to_string(number);

第一个排列是所有数字的排序排列。这个很容易获得 使用std::sort.

std::sort(s.begin(), s.end());

最后,使用std::next_permutation获取其他排列。一旦它得到最后一个,它将返回false并退出循环。

int n{0};
do {
++n;
std::cout << s << 'n';
} while (std::next_permutation(s.begin(), s.end()));
std::cout  << "Number of permutations: " << n;

现场示例

相关文章: