38 wins the Offer-- face questions: string arrangement

38 is inscribed: string arrangement
Title: enter a string, arranged to print all of the characters in the string. For example input string abc, abc print all strings of characters a, b, c can be arranged out, acb, bac, bca, cab and cba.

#include<iostream>
using namespace std;
void Permutation(char *pStr, char *pBegin){
	if(*pBegin=='\0') printf("%s\n", pStr);
	else{
		for(char* pCh=pBegin;*pCh!='\0';pCh++){
			char temp=*pCh;
			*pCh=*pBegin;
			*pBegin=temp;
			
			Permutation(pStr, pBegin+1);
			
			temp=*pCh;
			*pCh=*pBegin;
			*pBegin=temp;
		}
	}
}
void Permutation(char* pStr){
	if(pStr==NULL) return ;
	Permutation(pStr, pStr);
}
int main() {
	char pStr[]="abc";
	Permutation(pStr);
	return 0;
}

Related topics:

  • Enter an array of numbers containing 8, this determination it possible eight numbers are placed on the eight cube vertices such that three groups of four vertices and on the opposite side of the cube are equal.
    Here Insert Picture Description
    This corresponds to give a1, a2, a3, a4, a5, a6, a7 a8 all permutations and eight numbers, and then there is determined a certain topic are arranged in line with the given conditions, i.e., a1 + a2 + a3 + a4 == a5 + a6 + a7 + a8 , a1 + a3 + a5 + a7 == a2 + a4 + a6 + a8, and a1 + a2 + a5 + a6 == a3 + a4 + a7 + a8.
#include<iostream>
using namespace std;
bool CubVertex(int *A, int len, int begin){
	if(A==NULL || len!=8) return false;
	bool result=false;
	if(begin==len-1){
		if(A[0]+A[1]+A[2]+A[3]==A[4]+A[5]+A[6]+A[7] && A[0]+A[2]+A[4]+A[6]==A[1]+A[5]+A[3]+A[7] && A[0]+A[1]+A[4]+A[5]==A[2]+A[3]+A[6]+A[7]){
			for(int i=0;i<len;i++) {
				printf("%d ", A[i]);
			}
			printf("\n");
			result=true;
		}
	}else{
		for(int i=begin;i<len;i++){
			int temp=A[begin];
			A[begin]=A[i];
			A[i]=temp;
			
			result=CubVertex(A, len, begin+1);
			if(result) break;
			
			temp=A[begin];
			A[begin]=A[i];
			A[i]=temp;
		}
	}
	return result;
}
int main() {
	int A[8] = {1,2,3,1,2,3,2,2};
	int B[8] = {1,2,3,1,8,3,2,2};
	if(CubVertex(A,8,0))
		printf("Yes\n");
	else
		printf("No\n");
	if(CubVertex(B,8,0))
		printf("Yes\n");
	else
		printf("No\n");
	return 0;
}
  • n queens problem
#include<iostream>
using namespace std;
const int maxn=11;
int n,P[maxn],hashTable[maxn]={false},count=0;
void generateP(int index){
	if(index==n+1){
		count++;
		return ;
	}
	for(int x=1;x<=n;x++){
		if(hashTable[x]==false){
			bool flag=true;
			for(int pre=1;pre<index;pre++){
				if(abs(index-pre)==abs(x-P[pre])){
					flag=false;
					break;
				}
			}
			if(flag){
				P[index]=x;
				hashTable[x]=true;
				generateP(index+1);
				hashTable[x]=false;
			}
		}
	}
}
int main() {
	n=8;
	generateP(1);
	printf("%d", count);
	return 0;
}
Published 42 original articles · won praise 43 · views 1044

Guess you like

Origin blog.csdn.net/qq_35340189/article/details/104433391