您的位置:首页 > 其它

组合数(DFS)

2016-03-11 11:43 447 查看


组合数

时间限制:3000 ms  |  内存限制:65535 KB
难度:3

描述找出从自然数1、2、... 、n(0<n<10)中任取r(0<r<=n)个数的所有组合。

输入输入n、r。
输出按特定顺序输出所有组合。

特定顺序:每一个组合中的值从大到小排列,组合之间按逆字典序排列。
样例输入
5 3


样例输出
543
542
541
532
531
521
432
431
421
321


来源[苗栋栋]原创
上传者
苗栋栋

#include <vector>
#include <list>
#include <map>
#include <set>
#include <deque>
#include <queue>
#include <stack>
#include <bitset>
#include <algorithm>
#include <functional>
#include <cstdio>
#include <cstdlib>
#include <cstring>
#include <iostream>
#define N 11
using namespace std;
int n, ans
, visit
, m;

void dfs( int depth )
{
int i, j;
for ( i = m; i >= 1; i-- )
{
if ( depth > 1 && i > ans[depth - 1] )
continue;//cut
if ( !visit[i] )
{
visit[i] = 1;
ans[depth] = i;
if ( depth < n )
dfs( depth + 1 );
else{
for ( j = 1; j <= n; j++ )
cout << ans[j];
cout << endl;
}
visit[i] = 0;
}
}
}

int main()
{
cin >> m >> n;
memset( visit, 0, sizeof(visit) );
dfs( 1 );
return(0);
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: