遞歸實現組合型枚舉----------------遞歸與遞推

從 1~n 這 n 個整數中隨機選出 m 個,輸出所有可能的選擇方案。
輸入格式
兩個整數 n,mn,m ,在同一行用空格隔開。
輸出格式
按照從小到大的順序輸出所有方案,每行1個。
首先,同一行內的數升序排列,相鄰兩個數用一個空格隔開。
其次,對於兩個不同的行,對應下標的數一一比較,字典序較小的排在前面(例如1 3 5 7排在1 3 6 8前面)。
數據範圍
n>0n>0 ,

0≤m≤n0≤m≤n ,

n+(n−m)≤25n+(n−m)≤25
輸入樣例:
5 3

輸出樣例:
1 2 3
1 2 4
1 2 5
1 3 4
1 3 5
1 4 5
2 3 4
2 3 5
2 4 5
3 4 5

思考題:如果要求使用非遞歸方法,該怎麼做呢?

#include <iostream>
#include <cstdio>
#include <cstring>
#include <algorithm>
using namespace std;
const int N = 25;
int n, m;
int way[N];
void dfs(int u, int cnt){
 if (cnt + n - u + 1 < m)   return;
  if (cnt >= m){
  for(int i = 1; i <= m; i ++)
    printf("%d ", way[i]);
  puts("");
  return ;
 }
        for (int i = u ; i <= n; i ++){
     way[++ cnt] = i;
     dfs(i + 1, cnt);
     way[cnt --] = 0;
 }
}
int main(){
 cin >> n >> m;
 dfs(1, 0);
 return 0;
}
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章