21xrx.com
2025-04-02 02:39:15 Wednesday
文章检索 我的文章 写文章
C++ 排列组合实现
2023-06-27 05:55:54 深夜i     117     0
C++ 排列组合 实现

C++ 是一种流行的编程语言,广泛应用于各种领域。在编写程序时,排列组合是常见的问题之一。下面将介绍如何使用 C++ 实现排列组合。

排列是从 n 个不同的元素中,取出 m 个元素,按一定顺序排列成一列的方式。C++ 中可以使用标准库 algorithm 中的 next_permutation 函数来实现排列。下面是排列的一个简单实现示例:

#include<iostream>
#include<algorithm>
#include<vector>
using namespace std;
int main()
{
  vector<int> nums=2;
  sort(nums.begin(),nums.end());
  do
  {
    for(auto n:nums)
    
      cout<<n<<" ";
    
    cout<<endl;
  }while(next_permutation(nums.begin(),nums.end()));
  return 0;
}

在上面的代码中,首先定义了一个向量 nums,然后使用 sort 函数将其排序。接着使用 do-while 循环对 nums 进行排列,使用 next_permutation 函数进行排列操作,while 条件为排列成功返回 true,否则返回 false。最后输出所有的排列结果。

组合是从 n 个不同的元素中,取出 m 个元素,不考虑元素的顺序。C++ 中可以使用递归实现组合。下面是组合的一个简单实现示例:

#include<iostream>
#include<vector>
using namespace std;
void combine(vector<int>&nums,int start,int n,int m,vector<int>&path)
{
  if(path.size()==m)
  {
    for(auto n:path)
    
      cout<<n<<" ";
    
    cout<<endl;
    return;
  }
  for(int i=start;i<=n;i++)
  {
    path.push_back(nums[i-1]);
    combine(nums,i+1,n,m,path);
    path.pop_back();
  }
}
int main()
{
  vector<int> nums={1,2,3,4};
  vector<int> path;
  combine(nums,1,nums.size(),3,path);
  return 0;
}

在上面的代码中,首先定义了一个向量 nums 和一个 path,其中 nums 为需要选取的元素,path 记录组合的元素。接着定义 combine 函数递归实现组合,其中 start 表示开始选取的元素索引,n 表示元素总数,m 表示选取的元素个数,如果 path 的元素个数等于 m,则输出 path 中的所有元素。接着逐个将 nums 中的元素加入 path 中,对于每个加入的元素,递归调用函数进行下一步组合操作。当递归结束后,把 path 中的最后一个元素弹出。

以上是 C++ 中排列组合的实现方法,希望对读者有所帮助。

  
  

评论区

请求出错了