iis 网站模板下载,装修网站合作,如何发布自己的网站,获客引流100种方法1.
题目描述
排列与组合是常用的数学方法#xff0c;桐桐刚刚学会了全排列#xff0c;就想试试组合#xff0c;组合就是从n个元素中抽出r个元素#xff08;不分顺序且r≤n#xff09;#xff0c;我们可以简单地将n个元素理解为自然数1#xff0c;2#xff0c;……1.
题目描述
排列与组合是常用的数学方法桐桐刚刚学会了全排列就想试试组合组合就是从n个元素中抽出r个元素不分顺序且r≤n我们可以简单地将n个元素理解为自然数12…n从中任取r个数。
输入
两个整数n和r(1≤r≤n≤20)。
输出
输出所有的组合每一个组合占一行且其中的元素按由小到大的顺序排列每个元素占三个字符的位置所有的组合也按字典顺序。
样例输入 Copy
5 3样例输出 Copy 1 2 31 2 41 2 51 3 41 3 51 4 52 3 42 3 52 4 53 4 5
#include bits/stdc.h
using namespace std;
int n, r;
int ans[30];
void dfs(int st, int ed, int cnt)
{if (cnt r){for (int i 1; i r; i) printf(%3d, ans[i]);puts();return;}for (int i st; i ed; i){ans[cnt 1] i;dfs(i 1, ed, cnt 1);// ans[cnt 1] 0;}
}
int main()
{cin n r;dfs(1, n, 0);return 0;
}
全排列
#include bits/stdc.h
using namespace std;
const int N 10;
int path[N];
bool st[N]; // 当前位置是否已经走过
int n;
void dfs(int u)
{if (u n) // 已把所有位置填满可输出{for (int i 0; i n; i) printf(%d , path[i]);puts();return;}for (int i 1; i n; i){if (!st[i]){path[u] i; st[i] true;dfs(u 1);// path[u] 0; //因为path[u]的值会不断被覆盖所以恢不恢复都可以st[i] false;}}}
int main()
{scanf(%d, n);dfs(0);return 0;
}