硬币反转(递归) \( ̄︶ ̄*\))
查看原帖
硬币反转(递归) \( ̄︶ ̄*\))
749476
LuYouheng楼主2022/7/18 23:28

硬币反转(递归) ( ̄︶ ̄*))

辅助数组:a[n]用来记录各个硬币的状态

递归边界:n==2时,第一个不变,其余反转,输出;第二个不变,其余反转,输出

递归关系:n>2时,递归翻前n-2个;第n-1个不变,其余反转,输出;第n个不变,其余反转,输出

代码如下所示:

#include<bits/stdc++.h>
using namespace std;
int n;
void shuchu(int a[]){//输出各硬币状态的函数
	for(int i=0;i<=n-1;i++)cout<<a[i];
	cout<<endl;
}
void fanzhuan(int a[],int k){//反转函数,第k个不变,其余反转
	for(int i=0;i<=n-1;i++){
		if(i!=k-1)a[i]=1-a[i];
	}
}
void digui(int a[],int m){//递归函数
	if(m==2){//递归边界
		fanzhuan(a,1);
		shuchu(a);
		fanzhuan(a,2);
		shuchu(a);	
	}
	else{//递归关系
		digui(a,m-2);
		fanzhuan(a,m-1);
		shuchu(a);
		fanzhuan(a,m);
		shuchu(a);
	}
}
int main(){
	cin>>n;
	int a[n]={0};
   cout<<n<<endl;
	digui(a,n);
	return 0;
}
2022/7/18 23:28
加载中...