剑指Offer——面试题38:字符串的排列

面试题38:字符串的排列
题目:输入一个字符串,打印出该字符串中字符的所有排列。例如输入字符串abc,则打印出由字符a、b、c所能排列出来的所有字符串abc、acb、bac、bca、cab和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;
}

相关题目:

  • 输入一个含有8个数字的数组,判断有没有可能把这8个数字分别放到正方体的8个顶点上,使得正方体上三组相对的面上的4个顶点的和都相等。
    在这里插入图片描述
    这相当于先得到 a1、a2、a3、a4、a5、a6、a7和a8这8个数字的所有排列,然后判断有没有某一个排列符合题目给定的条件,即 a1+a2+a3+a4==a5+a6+a7+a8,a1+a3+a5+a7==a2+a4+a6+a8,并且 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皇后问题
#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;
}
发布了42 篇原创文章 · 获赞 43 · 访问量 1044

猜你喜欢

转载自blog.csdn.net/qq_35340189/article/details/104433391