zoukankan      html  css  js  c++  java
  • 【IT面试题004】全排列

    使用深度优先搜索

    /*
    
    套用深度优先搜索之全排列
    全排列 
    
    输入: n(<=26)
    输出:将 前n个小写字母全排列输出
    */
    
    #include "stdafx.h"
    
    #include <iostream>
    
    #include <string>
    #include <vector>
    using namespace std;
    
    int gN;
    const int MAX_ELEMENT = 10000;
    char solution[MAX_ELEMENT];
    int selected[26];
    int gCurNum; 
    int gSolCount;
    void PrintSolution()
    {
    	for (int i = 0;i < gN;i++)
    	{
    		cout << solution[i] << " ";
    	}
    	cout << endl;
    }
    void Go()
    {
    	if (gCurNum == gN)
    	{
    		gSolCount ++;
    		PrintSolution();
    		return;
    	}
    
    	for (char c = 'a';c < 'a' + gN;c++ )
    	{
    		if (selected[c] == 0)
    		{
    			gCurNum++;
    			solution[gCurNum - 1] = c;
    			selected[c] = 1;
    			Go();
    			gCurNum --;
    			selected[c] = 0;
    		}
    	}
    }
    int _tmain(int argc, _TCHAR* argv[])
    {
    
    	gN = 9;
    	memset(selected,0,sizeof(selected));
    	gCurNum = 0;
    	gSolCount = 0;
    	Go();
    	cout << gSolCount << endl;
    }
    
     
    还有一个比较巧妙的递归版本
    void Swap(char & a,char &b)
    {
    	char t = a;
    	a = b;
    	b = t;
    }
    void Permutation(char * pElement,int N,int startIdx)
    {
    	if (startIdx == N)
    	{
    		gSolCount ++;
    		//PrintElement(pElement,N);
    		return;
    	}
    
    	Permutation(pElement,N,startIdx + 1);
    	for (int i = startIdx + 1;i < N;i++)
    	{
    		Swap(pElement[startIdx],pElement[i]);
    		Permutation(pElement,N,startIdx + 1);
    		Swap(pElement[startIdx],pElement[i]);
    	}
    }
    void TestPermutation()
    {
    	gN = 9;
    	gSolCount = 0;
    	char elements[26];
    	for (int i = 0;i<gN;i++)
    	{
    		elements[i] = 'a' + i;
    	}
    
    	Permutation(elements,gN,0);
    	cout << gSolCount << endl;
    }
  • 相关阅读:
    scnner02 (nextLine)
    Scanner01
    Spring 框架 (初学)
    查询自己写了多少行代码
    jdbc事务
    jdbc(预编译插入数据)
    jdbc(java连接数据库)
    监听器扩展
    listener(监听器)
    Filter过滤器
  • 原文地址:https://www.cnblogs.com/speedmancs/p/2072753.html
Copyright © 2011-2022 走看看