Recursion Final

This commit is contained in:
e2hang
2025-07-18 09:32:21 +01:00
parent 8d7eb8c99c
commit ae3f0aecbb
4 changed files with 44 additions and 11 deletions

BIN
Recursion/P27_All_Sorted Executable file

Binary file not shown.

View File

@@ -1,9 +1,38 @@
//For a,b,c we have sort abc acb bac bca cab cba(6 kinds) This Program is to sort all of the kinds
#include <iostream>
using namespace std;
// 递减n叉树
// 可能需要包展开这里先不写先以3个为主
template<typename T>
T* sort(int n, int l, T* tmp, bool* used, T* arr){
if(n == l){
cout << "[";
for(int i = 0;i < n; i++){
cout << tmp[i] <<" ";
}
cout << "]" << endl;
}
for(int i = 0;i < l; i++){
if(used[i] == false){
tmp[n] = arr[i];
used[i] = true;
sort(n + 1, l, tmp, used, arr);
used[i] = false; //是否可以删除?不可以,回溯本节点要用
}
}
}
int main() {
int n;
cin >> n;
int* tmp = new int[n];
int* arr = new int[n];
for(int i = 0;i < n; i++){
cin >> arr[i];
}
bool* used = new bool[n];
sort(0, n, tmp, used, arr);
return 0;
}
}

Binary file not shown.

View File

@@ -6,21 +6,24 @@ using namespace std;
//n: 本次递归数组长度
//l: 给定数组长度
template <class T>
T* sub(int m ,int n, int l, T* x){
T* tmp = new T [l];
if(m == l){
for(int i = 0; i < l; i++){
cout << tmp[i] << endl;
T* sub(int m ,int n, int l, T* x, T* tmp){
if(m == l)
{
cout << "[ ";
for(int i = 0; i < n; i++){
cout << tmp[i] << " ";
}
cout << " ]" << endl;
return tmp;
}
//不选a[i]
sub(m + 1, n, l, x);
sub(m + 1, n, l, x, tmp);
//选a[i]
tmp[n] = x[m];
sub(m + 1, n + 1, l, x);
sub(m + 1, n + 1, l, x, tmp);
}
@@ -34,8 +37,9 @@ int main(){
for(int i = 0; i < num ; i++){
p[i] = new double[n];
}
double* tmp = new double[n];
double arr[] = {1, 2, 3, 4, 5};
sub(0, 0, 5, arr);
sub(0, 0, 5, arr, tmp);
return 0;
}