📜  制作所有大小为k的组合

📅  最后修改于: 2021-04-29 07:55:30             🧑  作者: Mango

给定两个数字n和k,您必须找到1…n中k个数字的所有可能组合。

例子:

Input : n = 4 
        k = 2
Output : 1 2 
         1 3 
         1 4 
         2 3 
         2 4 
         3 4 

Input : n = 5 
        k = 3
Output : 1 2 3 
         1 2 4 
         1 2 5 
         1 3 4 
         1 3 5 
         1 4 5 
         2 3 4 
         2 3 5 
         2 4 5 
         3 4 5 

我们在下面的文章中讨论了一种方法。

在大小为n的给定数组中打印r元素的所有可能组合

在这种情况下,我们使用基于DFS的方法。我们想要从1到n的所有数字。我们首先将tmp_vector中的所有数字从1推到k,并且当k等于0时,我们将tmp_vector的所有数字推到ans_vector。之后,我们从tmp_vector中删除最后一个元素,并进行所有剩余的组合。

// C++ program to print all combinations of size
// k of elements in set 1..n
#include 
using namespace std;
  
void makeCombiUtil(vector >& ans,
    vector& tmp, int n, int left, int k)
{
    // Pushing this vector to a vector of vector
    if (k == 0) {
        ans.push_back(tmp);
        return;
    }
  
    // i iterates from left to n. First time
    // left will be 1
    for (int i = left; i <= n; ++i)
    {
        tmp.push_back(i);
        makeCombiUtil(ans, tmp, n, i + 1, k - 1);
  
        // Popping out last inserted element
        // from the vector
        tmp.pop_back();
    }
}
  
// Prints all combinations of size k of numbers
// from 1 to n.
vector > makeCombi(int n, int k)
{
    vector > ans;
    vector tmp;
    makeCombiUtil(ans, tmp, n, 1, k);
    return ans;
}
  
// Driver code
int main()
{
    // given number
    int n = 5;
    int k = 3;
    vector > ans = makeCombi(n, k);
    for (int i = 0; i < ans.size(); i++) {
        for (int j = 0; j < ans[i].size(); j++) {
            cout << ans.at(i).at(j) << " ";
        }
        cout << endl;
    }
    return 0;
}

输出:

1 2 3 
1 2 4 
1 2 5 
1 3 4 
1 3 5 
1 4 5 
2 3 4 
2 3 5 
2 4 5 
3 4 5