#include <iostream>
using namespace std;
char str[2200][2200];
int num[10] = {0, 1, 3, 9, 27, 81, 243, 729, 2187};
void func(int x,int y, int n){
if(n == 1){
str[x][y] = 'X';
return;
}
func(x, y, n - 1);
func(x, y + num[n] / 3 * 2, n - 1);
func(x + num[n] / 3 * 2, y, n - 1);
func(x + num[n] / 3 * 2, y + num[n] / 3 * 2, n - 1);
func(x + num[n] / 3, y + num[n] / 3, n - 1);
}
int main(){
int n,flag = 0;
func(1,1,7);
while(cin >> n){
if(n == -1) break;
for (int i = 1; i <= num[n]; i++) {
for (int j = 1; j <= num[n]; j++) {
if (str[i][j] == 'X') cout << "X";
else cout << ' ';
}
cout << endl;
}
cout << "-"<<endl;
}
return 0;
}
235.递归实现指数型枚举
深度优先搜索(缩写DFS)有点类似广度优先搜索,也是对一个连通图进行遍历的算法。它的思想是从一个顶点V0开始,沿着一条路一直走到底,如果发现不能到达目标解,那就返回到上一个节点,然后从另一条路开始走到底,这种尽量往深处走的概念即是深度优先的概念。
递归回溯法算法框架[一]
int dfs(int k)
{
for (i=1;i<=算符种数;i++)
if (满足条件)
{
保存结果
if (到目的地) 输出解;
else dfs(k+1);
恢复:保存结果之前的状态{回溯一步}
}
}
递归回溯法算法框架[二]
int Search(int k)
{
if (到目的地) 输出解;
else
for (i=1;i<=算符种数;i++)
if (满足条件)
{
保存结果;
dfs(k+1);
恢复:保存结果之前的状态{回溯一步}
}
}
/*************************************************************************
> File Name: 235.cpp
> Author:
> Mail:
> Created Time: 2020年04月02日 星期四 00时10分56秒
************************************************************************/
#include <iostream>
using namespace std;
int n,cnt, num[15];
void func(int x){
for(int i = x; i <= n; i++){
num[cnt++] = i;
for(int j = 0; j < cnt; j++){
j && cout << " ";
cout << num[j];
}
cout << endl;
func(i+1);
cnt--;
}
}
int main(){
cin >> n;
func(1);
}
#include <iostream>
using namespace std;
int n, m, num[15], cnt;
void func(int s, int left) {
if (left == 0) {
for (int i = 0; i < cnt; i++) {
if (i) cout << " ";
cout << num[i];
}
cout << endl;
return ;
}
for (int i = s; i <= n - left + 1; i++) {
num[cnt] = i;
cnt++;
func(i + 1, left - 1);
cnt--;
}
}
int main() {
cin >> n >> m;
func(1, m);
return 0;
}
#include <iostream>
using namespace std;
int n, num[15], cnt, mark[15];
void func(int left) {
if (left == 0) {
for (int i = 0; i < cnt; i++) {
if (i) cout << " ";
cout << num[i];
}
cout << endl;
return ;
}
for (int i = 1; i <= n; i++) {
if (mark[i] == 0) {
mark[i] = 1;
num[cnt] = i;
cnt++;
func(left - 1);
cnt--;
mark[i] = 0;
}
}
}
int main() {
cin >> n;
func(n);
return 0;
}
#include <iostream>
using namespace std;
int func(int s, int left_num, int left_cnt) {
if (left_cnt == 0) {
if (left_num == 0) return 1;
return 0;
}
int ans = 0;
for (int i = s; i <= left_num; i++) {
ans += func(i, left_num - i, left_cnt - 1);
}
return ans;
}
int main() {
int n, m;
cin >> n >> m;
cout << func(1, n, m) << endl;
return 0;
}
借鉴:
https://www.cnblogs.com/SeanOcean/p/10975590.html
https://www.cnblogs.com/DWVictor/p/10048554.html