首页 > 代码库 > 不同元素的排列与组合

不同元素的排列与组合

#include<iostream>
#include<vector>
#include<string>
#include<algorithm>
#include<numeric>
using namespace std;
 
vector<vector<int> > ret;
vector<int> sub;
int num = 0;

void helper(int* str, int n,int i) ///递归求组合
{
  if(i == n)
  {
    ret.push_back(sub);
    return;
  }
  helper(str, n,i+1);
  sub.push_back(str[i]);
  helper(str, n,i+1);
  sub.pop_back(); ///看来这个要恢复场景~
}

void helper2(int* str, int n,int i)
{
  if(i == n - 1)
  {
      num++;
      cout<<num<<endl;
      return ;
  }

   for(int j = i;j < n;j++)
  {
    swap(str[i],str[j]);
    helper2(str, n,i + 1);
    swap(str[i],str[j]);
  }

}



int main()
{
    ret.clear();
    sub.clear();
    int str[] = {1,2,3,4,5};
    helper2(str, 5, 0);
    //for(int i = 0;i< ret.size();i++)
    //{
    //    for(int j = 0;j< ret[i].size();j++)
    //        cout<<ret[i][j]<<" ";
    //        cout<<endl;
    //}
}