回溯算法
输出某个数组元素所有的排列组合
void hs(vector<vector<int>>& z,vector<int>& n, int* num,int m)
{
if (n.size() == m)
{
z.push_back(n);
return;
}
for (int i = 0; i < m; i++)
{
int x = count(n.begin(), n.end(), num[i]);
if (x) continue;
n.push_back(num[i]);
hs(z, n, num, m);
n.pop_back();
}
}
void back(int n)
{
vector<vector<int>> z;
vector<int> nn;
int* num=new int[n];
for (int i = 0; i < n; i++)
{
num[i] = i + 1;
}
hs(z, nn, num, n);
}
输出数组所有排列组合(有重复元素)
void charback(vector<vector<char>>& ccc,vector<char>& cc,char* c,int size,int* flag)
{
if(cc.size()==size)
{
vector<char> cc1;
for(int i=0;i<size;i++)
{
cc1.push_back(c[cc[i]]);
}
int x = count(ccc.begin(),ccc.end(),cc1);
if(!x) ccc.push_back(cc1);
return;
}
for(int i=0;i<size;i++)
{
int x = count(cc.begin(),cc.end(),flag[i]);
if(x) continue;
cc.push_back(flag[i]);
charback(ccc,cc,c,3,flag);
cc.pop_back();
}
}
void a()
{
char* c={'a','a','b'};
vector<char> cc;
vector<vector<char>> ccc;
int flag[3] = {0,1,2};
charback(ccc,cc,c,3,flag);
}
输出数组所有的子集
void ziji(int* i,int* flag,int size)
{
if(size==3)
{
for(int i=0;i<3;i++)
{
if(flag[i]==1) cout<<i[i]<<" ";
}
cout<<endl;
return;
}
flag[size]=1;
ziji(i,flag,size+1);
flag[size]=0;
ziji(i,flag,size+1);
}
void a()
{
int i[3]={1,2,3};
int flag[3]={0,0,0};
ziji(i,flag,0);
}
八皇后问题
bool pan(char** q, int row, int col,int n)
{
for (int i = row - 1; i >= 0; i--)
{
if (q[i][col] == 'Q') return false;
}
for (int i = row - 1, j = col + 1; i >= 0 && j < n; i--, j++)
{
if (q[i][j] == 'Q') return false;
}
for (int i = row - 1, j = col - 1; i >= 0 && j >= 0; i--, j--)
{
if (q[i][j] == 'Q') return false;
}
return true;
}
//h row l col
void queenback(vector<char**>& c,char** q,int row,int n)
{
if (row == n)
{
char** q1 = new char* [n];
for (int i = 0; i < n; i++)
{
q1[i] = new char[n];
}
for (int i = 0; i < n; i++)
{
for (int j = 0; j < n; j++)
{
q1[i][j] = q[i][j];
}
}
c.push_back(q1);
return;
}
for (int i = 0; i < n; i++)
{
if (!pan(q,row,i,n)) continue;
q[row][i] = 'Q';
queenback(c, q, row + 1, n);
q[row][i] = '.';
}
}
void eightqueen(int n)
{
vector<char**> c;
char** q = new char*[n];
for (int i = 0; i < n; i++)
{
q[i] = new char[n];
}
for (int i = 0; i < n; i++)
{
for (int j = 0; j < n; j++)
{
q[i][j] = '.';
}
}
queenback(c, q, 0, n);
cout << c.size()<<endl;
for (int i = 0; i < c.size(); i++)
{
for (int j = 0; j < n; j++)
{
for (int k = 0; k < n; k++)
{
cout << c[i][j][k] << " ";
}
cout << endl;
}
cout << endl;
}
}