• 排列与组合的实现


    排列与组合,递归实现

    // Permutation and Combination.cpp : 定义控制台应用程序的入口点。
    //
    
    #include "stdafx.h"
    #include<vector>
    #include<set>
    #include<iostream>
    
    using namespace std;
    
    vector<vector<int>>aaa;
    set<set<int>>solu;
    
    void do_once(vector<int>&selected, vector<int>&remain)
    {
    	if (remain.empty())
    	{
    		aaa.push_back(selected);
    		for (int i = 0; i < selected.size(); i++)
    			cout << selected[i] << ",";
    		cout << endl;
    		return;
    	}
    	for (int i = 0; i < remain.size(); i++)
    	{
    		vector<int>se = selected,re=remain;
    		se.push_back(re[i]);
    		re.erase(re.begin()+i);
    		do_once(se, re);
    	}
    }
    
    void Permutation(int*input, int len)//全排列
    {
    	aaa.clear();
    	vector<int>remain, selected;
    	for (int i = 0; i < len; i++)
    		remain.push_back(input[i]);
    	do_once(selected, remain);
    	cout << "共有"<<aaa.size()<<"种排列" << endl;
    }
    
    
    
    
    void select(set<int>&selected, vector<int>&remain, int toselect)
    {
    	if (selected.size()==toselect)
    	{
    		if (solu.find(selected) == solu.end())
    		{
    			solu.insert(selected);
    			for (set<int>::iterator it = selected.begin(); it != selected.end(); it++)
    				cout << *it << ",";
    			cout << endl;
    		}
    		return;
    	}
    	for (int i = 0; i < remain.size(); i++)
    	{
    		vector<int> re = remain;
    		set<int>se = selected ;
    		se.insert(re[i]);
    		re.erase(re.begin() + i);
    		select(se, re,toselect);
    	}
    }
    void Combination(int*input,int len,int toselect)//组合
    {
    	solu.clear();
    	vector<int>remain;
    	set<int>selected;
    	for (int i = 0; i < len; i++)
    		remain.push_back(input[i]);
    	select(selected, remain, toselect);
    	cout << "共有" << solu.size() << "种组合" << endl;
    }
    
    int _tmain(int argc, _TCHAR* argv[])
    {
    	int aa[5] = { 0, 1, 2 ,3,4};
    	Permutation(aa, 5);
    
    	//Combination(aa, 5, 2);
    
    	system("pause");
    	return 0;
    }
    


    版权声明:

  • 相关阅读:
    转:mac下安装homebrew
    jdk1.7下载路径
    转: Mac 使用ADT的问题
    转:mac下安装Sublime Text
    转: SVN和Git的一些用法总结
    转: SVN使用教程总结(图文丰富,相当详细)
    转:Tortoise SVN 版本控制常用操作知识
    Android Java混淆(ProGuard)
    转:美团Android资源混淆保护实践
    【IPC进程间通讯之三】内存映射文件Mapping File
  • 原文地址:https://www.cnblogs.com/walccott/p/4956879.html
Copyright © 2020-2023  润新知