DFS_组合序列

 1 #include <iostream>
 2 #include <cstdio>
 3 #include <cstring>
 4 #include <cstdlib>
 5 #include <algorithm>
 6 #include <vector>
 7 #define sc(x) scanf("%d",&(x))
 8 #define sc2(x,y) scanf("%d%d", &(x), &(y))
 9 #define pn printf("%\n")
10 #define PF(x) printf("%d ",x)
11 #define pf(x) printf("%d\n",x)
12 #define CL(x, y) memset(x, y, sizeof(x))
13 #define FOR(i,b,e)  for(int i = b; i <= e; i++)
14 #define max(a, b) (a > b ? a : b)
15 #define ABS(a, b) (a > b ? a - b : b - a)
16 using namespace std;
17 const int MAX = 25;
18 int ans[MAX], n, v, r;
19 void show();
20 void DFS(int pos, int v);
21 int main()
22 {  
23     sc2(n, r);
24     DFS(0, 1);
25     return 0;
26 }
27 void DFS(int pos, int v)
28 {
29     if(pos == r)
30     {
31         show();
32         return ;
33     }
34     if(v > n) return ;
35     FOR(i,v,n)
36     {
37         ans[pos] = i;
38         DFS(pos+1, i+1);
39     }
40 }
41 void show()
42 {
43     FOR(j,0,r-1)
44     PF(ans[j]);
45     cout << endl;    
46 }
View Code

题意:排列与组合是常用的数学方法,其中组合就是从N个元素中抽出R个元素(不分顺序且R<=N),我们可以简单地将N个元素理解为1,2,…,N,从中任取R个数。

例如N=5,R=3,所有组合为:123       124     125       134      135      145       234       235      245        345

 

思路:回溯先放第一个数,再在第一个数字的基础上放第二个数字,再在第二个数字的基础上放第三个数字

posted @ 2015-04-10 18:29  PastLIFE  阅读(274)  评论(0编辑  收藏  举报