1.全排列递归
1 #include<iostream> 2 using namespace std; 3 int n, arr[10], ifuse[10] = { 0,0,0,0,0,0,0,0,0,0 }; 4 void p() 5 { 6 for (int k = 1; k <= n; k++) 7 { 8 cout << arr[k] << " "; 9 }cout << endl; 10 } 11 void f(int set) 12 { 13 if (set > n)return; 14 for (int i = 1; i <= n; i++)//每个位置上遍历1~n 15 { 16 if (ifuse[i] == 0) 17 { 18 arr[set] = i; 19 ifuse[i] = 1; 20 f(set +1); 21 } 22 else continue; 23 if (set == n)p(); 24 ifuse[i] = 0; 25 } 26 } 27 int main() 28 { 29 cin >> n; 30 f(1); 31 }
2.组合型递归
从1~m个数里选出n个数进行排列;
1 #include<iostream> 2 using namespace std; 3 int m, n, arr[10]; 4 //一行一行的输出 5 void p() 6 { 7 for (int k = 0; k < n; k++) 8 { 9 cout << arr[k] << " "; 10 }cout << endl; 11 } 12 //第i个位置最小值是j 13 void f(int i, int j) 14 { 15 if (i >= n)return; 16 for (int a = j; a <= m - n + i + 1; a++) 17 { 18 arr[i] = a; 19 // cout<<arr[i]<<" "; 20 f(i + 1, a + 1); 21 if (i == n - 1) p(); 22 } 23 } 24 int main() 25 { 26 cin >> m >> n; 27 f(0, 1); 28 }
3.指数型递归
1 //指数型递归 2 #include<iostream> 3 using namespace std; 4 int n, arr[10]; 5 void p(int i) 6 { 7 for (int k = 0; k <= i; k++) 8 { 9 cout << arr[k] << " "; 10 }cout << endl; 11 } 12 //第i个位置的最小值是j 13 void f(int i, int j, int n) 14 { 15 if (j > n)return; 16 for (int a = j; a <= n; a++) 17 { 18 arr[i] = a; 19 p(i); 20 f(i + 1, a + 1, n); 21 } 22 } 23 int main() 24 { 25 cin >> n; 26 f(0, 1, n); 27 }
标签:10,arr,递归,int,namespace,include From: https://www.cnblogs.com/hello-205112/p/17715941.html