全排列/递归/八皇后问题

分别交换第1个元素与第2、3、4、5..len-1个元素
void permutation(char *str,int begin,int len){

	

	if(len==1){

		printf("%s\n",str);

		count++;

		return;	

	}

	char  tmp = str[begin];

	for(int i=0;i<len;i++){

		char  tmp2=str[begin+i];

		str[begin] = tmp2;

		str[begin+i] = tmp;

		permutation(str,begin+1,len-1);

		str[begin] = tmp;

		str[begin+i]=tmp2;

	}

	

}
	
 
        char str[6];

	strcpy(str,"12345");

	permutation(str,0,5);



求所有组合:http://zhedahht.blog.163.com/blog/static/2541117420114172812217/
 

void Combination(char* string, int number, vector<char>& result);

void Combination(char* string)



{

	

    if(string == NULL)

		

        return;

	

	

	

    int length = strlen(string);

	

    vector<char> result;

	

    for(int i = 1; i <= length; ++ i)

		

    {

		

        Combination(string, i, result);

		

    }

	

}







void Combination(char* string, int number, vector<char>& result)



{

	

    if(number == 0)

		

    {

		

        vector<char>::iterator iter = result.begin();

		

        for(; iter < result.end(); ++ iter)

			

            printf("%c", *iter);

		

        printf("\n");

		

		

		

        return;

		

    }

	

	

	

    if(*string == '\0')

		

        return;

	

	

	

//一个字符有两种选择
    result.push_back(*string);

	

    Combination(string + 1, number - 1, result);



    result.pop_back();	

    
    Combination(string + 1, number, result);

	

}

----------------------------------------------------------------------------

八皇后问题:col,row+col,row-col三个标记数组

// 8QUEEN.cpp : Defines the entry point for the console application.

//



#include "stdafx.h"

#include <iostream>

using namespace std;

const int SIZE = 8;

const int OFFSET = SIZE -1;

const int FLAT_SIZE = 3*SIZE-2;//2*(SIZE-1)+(SIZE-1)+1

int sov[SIZE];

bool hasa[FLAT_SIZE]={false};

bool hasb[FLAT_SIZE]={false};

bool hasc[SIZE]={false};

bool couldStand(int r,int c){

	

	return !hasc[c]&&!hasa[r+c+OFFSET]&&!hasb[r-c+OFFSET];

}

int m_count = 0;

void t(int r){

	

	

	for(int c=0;c<SIZE;c++){	

		

		if(couldStand(r,c)){

			sov[r]=c;

			hasa[r+c+OFFSET]=true;

			hasb[r-c+OFFSET]=true;

			hasc[c]=true;

			if(r==OFFSET){

				for(int i=0;i<SIZE;i++)

					printf("%d ",sov[i]+1);

				printf("\n");

				m_count++;

			}else t(r+1);

			hasa[r+c+OFFSET]=false;

			hasb[r-c+OFFSET]=false;

			hasc[c]=false;

		}

	}

	



}

int main(int argc, char* argv[])

{

	memset(hasc,false,sizeof(hasc));

	t(0);

	printf("Hello World %d!\n",m_count);

	return 0;

}

你可能感兴趣的:(全排列)