【问题标题】:Print all subsets of given size of a set and count the subset打印一组给定大小的所有子集并计算子集
【发布时间】:2019-09-16 21:09:15
【问题描述】:

生成具有不同元素的给定数组的所有可能大小为 r 的子集。 在获得具有不同元素的给定数组的所有可能大小为 r 的子集后,我需要帮助来计算子集。生成后如何计算不同元素的子集

    #include <bits/stdc++.h> 
    using namespace std;
    void combinationUtil(int arr[], int n, int r, int index, int data[], int i); 

    void printCombination(int arr[], int n, int r) 
    { 
        int data[r]; 

        combinationUtil(arr, n, r, 0, data, 0); 
    } 
    void combinationUtil(int arr[], int n, int r, int index,int data[], int i) 
    { 
        int c=0; 
        if (index == r) { 
            for (int j = 0; j < r; j++) {
                printf("%d ", data[j]); 
            }
            printf("\n"); 
            return; 
        } 

        if (i >= n) 
            return; 

        data[index] = arr[i]; 
        combinationUtil(arr, n, r, index + 1, data, i + 1); 
        combinationUtil(arr, n, r, index, data, i + 1); 
    } 

    int main() 
    { 
        int arr[] = { 0,1,2,3,4}; 
        int r = 2; 
        int n = sizeof(arr) / sizeof(arr[0]); 
        printCombination(arr, n, r); 
        return 0; 
    }

output 
0 1
0 2
0 3
0 4
1 2
1 3
1 4
2 3
2 4
3 4
number of subset 10

【问题讨论】:

  • 1) int data[r]; -- 这不是有效的 C++。 2) #include &lt;bits/stdc++.h&gt; -- 使用正确的标题,而不是这个。 3)这个问题是通过使用std::next_permutation和其他一些项目来解决的,都没有递归。
  • 数组的大小和k长度如何

标签: c++


【解决方案1】:

让我们解决这个问题:next_permutation。这将置换输入,当所有置换都被访问时返回false
给定排序后的输入:int arr[] 我们可以这样做:

do {
    copy(cbegin(arr), cend(arr), ostream_iterator<int>(cout, " "));
    cout << endl;
} while(next_permutation(begin(arr), end(arr)));

Live Example

此示例假定输入是唯一的,在这种情况下,组合和排列是相同的。如果您没有唯一的输入,您实际上是在要求这些数字的组合next_combination 已在此处使用:http://www.open-std.org/jtc1/sc22/wg21/docs/papers/2008/n2639.pdf 如果您发现您没有唯一输入并使用它,则可以复制该实现。您还可以在此处了解有关next_combination 的更多信息:https://stackoverflow.com/a/35215540/2642059

【讨论】:

  • 是的,但我认为 OP 想要组合。您仍然使用next_permutation,但排列将在指向arr 中某些值的布尔数组上。
  • 这是公平的,我假设唯一的数字。我会更新以澄清。
  • #include #include #include int main() { int n, r;标准::cin >> n;标准::cin >> r; std::vector v(n); std::fill(v.begin(), v.begin() + 2, true);诠释 c=0; do { for (int i = 0; i
  • @chitaranjanpradhan -- 在原始问题中发布代码,或者如果您有答案,请将其发布在单独的答案中。不要在评论部分发布所有代码。
  • @chitaranjanpradhan 所以看起来就像在 cmets 中所说的那样,您正在寻找 next_combination 而不是 next_permutation。遗憾的是,这还没有被标准接受。当我需要它时,我只是从该提案中复制了实现并使用它。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2011-06-06
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多