【问题标题】:Getting all possible combinations of an integrer array in C++在 C++ 中获取整数数组的所有可能组合
【发布时间】:2020-11-08 18:27:24
【问题描述】:

我有一个整数数组,例如:a[1,2,3]。我想获得这些数字的所有可能组合,它们不会重复,可能是递归。

我在这里看到了用字符串完成的类似操作:Get all combinations without duplicates,但不知道如何在不使用任何标准算法的情况下使其适应整数。

所以我想要这样的输出:{1},{2},{3},{1,2},{2,3},{1,3},{1,2,3}

提前致谢!

【问题讨论】:

  • 对于排列使用std::next_permutation,对于组合也使用它;)
  • @idclev463035818 标签recursion(和其他线索)表明这必须在不使用标准算法的情况下完成
  • cppreference可能的实施 会议可能会为您提供一些关于如何从头开始实施您的版本的线索。
  • @VladFeinstein 您也可以将std::next_permutation 与递归一起使用。我知道练习经常有奇怪的要求,比如不允许标准算法,但是当 OP 没有提到它们时,这并不能让我断言这些奇怪的要求。如果没有标准算法,问题中应该提到它
  • 是的,所有标准算法都已出局。感谢您告诉我,因为我不知道...我从这里得到了一些不错的代码:geeksforgeeks.org/heaps-algorithm-for-generating-permutations 我只需要以某种方式对其进行修改,它还可以输出不使用所有数字的可能性。

标签: c++ arrays recursion integer combinations


【解决方案1】:

您可以使用来自<algorithms> 库的std::next_permutation 实现具有可比较元素的列表的所有排列。

cppreference 有一篇很好的文章:https://en.cppreference.com/w/cpp/algorithm/next_permutation

我们可以使用代码示例来解决您的问题。

#include <algorithm>
#include <string>
#include <iostream>
#include <vector>

void print_vector(const std::vector<int>& array) {
    for (const int item : array)
    {
        std::cout << item << " ";
    }
    std::cout << std::endl;
}
 
int main()
{
    std::vector<int> a({ 5,1,8,7,2 });
    std::sort(a.begin(), a.end());
    do {
        print_vector(a);
    } while(std::next_permutation(a.begin(), a.end()));
}

【讨论】:

    【解决方案2】:

    您可以使用std::next_permuation 来实现您的目标。 请记住,在开始使用此算法之前,您需要对数组进行排序。 循环将在std::next_permuation 第一次返回 false 时退出。 如果数组在您开始std::next_permuation 循环时未排序,则进入循环时您将错过所有字典顺序低于当前数组的数组。

        int main()
        {
            std::vector<int> a = { 5,1,8,7,2 };
            std::sort(a.begin(), a.end());
            std::cout << "Possible permutations :\n";
            do {
                for (auto o : a)
                    std::cout << o;
                std::cout << std::endl;
            } while (std::next_permutation(a.begin(), a.end()));
            return 0;
        }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2022-01-23
      • 2012-03-20
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多