【问题标题】:how to find all permutations of an n digit number without using array or function in c++如何在不使用c ++中的数组或函数的情况下找到n位数字的所有排列
【发布时间】:2018-09-21 19:25:27
【问题描述】:

我无法让这段代码按我想要的方式工作。任务是编写一个程序,打印输入的数字 n (1

#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;
    }
}

【问题讨论】:

  • 在这里使用一致的缩进会有很大帮助,否则你会迷失在复杂性中。
  • 我有点难以理解您的预期输出,如果我为 n 输入 8,我希望输出是什么?
  • 预期输出将是 40320 的排列数,然后是从 1 到 8 的所有数字排列(12345678,13245678...)。
  • 你知道std::next_permutation吗?
  • std::next_permutation 不需要数组吗?

标签: c++ permutation


【解决方案1】:

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

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;

Live example

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2018-02-09
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-09-05
    相关资源
    最近更新 更多