zoukankan      html  css  js  c++  java
  • 排列组合的代码总结篇

    #include <iostream>
    #include <vector>
    using namespace std;
    void my_swap(vector<char> &a,int i,int j){
        int temp=a[i];
        a[i]=a[j];
        a[j]=temp;
    }
    
    vector<char> v;
    int n;
    void printPremutationRepeat(int pStart,vector<char> temp){
        if(pStart==n){
            for (int i = 0; i < temp.size(); ++i)
            {cout<<temp[i];}
            cout<<" ";
            return;
        }
        
        for (int i = 0; i < 3; ++i)
        {
            temp.push_back(v[i]);
            printPremutationRepeat(pStart+1,temp);
            temp.pop_back();
        }
    }
    
    void printPremutationNoRepeat(int pStart,vector<char> temp){
        if(pStart==n){
            for (int i = 0; i < temp.size(); ++i)
            {cout<<temp[i];}
            cout<<" ";
            return;
        }
        
        for (int i = pStart; i < 3; ++i)
        {
            my_swap(v,i,pStart);
            temp.push_back(v[pStart]);
            printPremutationNoRepeat(pStart+1,temp);
            temp.pop_back();
            my_swap(v,i,pStart);
            
        }
    }

    /*组合特殊一点,实际这里是两个序列,待选序列v,和n个位置已选的序列。 以n=2为例,即从abcde中选2个字母形成组合。 那么pStart是abcde的指针, dep是形成的组合temp的指针 这里递归含义:固定第字母a,放在第一个位置,然后对之后的序列再进行组合,即从bcde中选一个 固定第字母b,放在第一个位置,那么就是从cde中选一个 第二次并不是从第0个位置开始,而是从b所在的角标1,开始的,所以pStart的值是i+1 */ void printCombination(int n,int dep,int pStart,vector<char> temp){ if(dep==n){ for (int i = 0; i < temp.size(); ++i) {cout<<temp[i];} cout<<" "; return; } for (int i = pStart; i < 3; ++i) { temp.push_back(v[i]); printCombination(n,dep+1,i+1,temp); temp.pop_back(); } } int main(){ v.push_back('a'); v.push_back('b'); v.push_back('c'); n=v.size(); vector<char> temp; cout<<"abc的可重复全排列是:"<<endl; printPremutationRepeat(0,temp); cout<<endl; cout<<"abc的全排列是:"<<endl; printPremutationNoRepeat(0,temp); cout<<endl; cout<<"abc的组合是:"<<endl; for (int i=1; i<=3; ++i) { printCombination(i,0,0,temp); } cout<<endl; return 0; }
     
  • 相关阅读:
    秒杀多线程第八篇 经典线程同步 信号量Semaphore
    SURF特征
    (最短路径算法整理)
    中国大推力矢量发动机WS15 跨入 世界先进水平!
    SQL Profile 总结(一)
    Spring下@ResponseBody响应中文内容乱码问题
    Ubuntu12.04下jamvm1.5.4+classpath-0.98成功执行 helloworld.class
    【2012.1.24更新】不要再在网上搜索eclipse的汉化包了!
    [数据结构] N皇后问题
    DG之主库、备库切换(物理备库)
  • 原文地址:https://www.cnblogs.com/fightformylife/p/4213095.html
Copyright © 2011-2022 走看看