洛穀P1157 組合的輸出

來源:互聯網
上載者:User

標籤:

洛穀1157 組合的輸出

題目描述

排列與組合是常用的數學方法,其中組合就是從n個元素中抽出r個元素(不分順序且r<=n),我們可以簡單地將n個元素理解為自然數1,2,…,n,從中任取r個數。
    現要求你不用遞迴的方法輸出所有組合。
    例如n=5,r=3,所有組合為:
    l 23    l 2 4    1 25    l 3 4    l 35    1 4 5    2 34    2 3 5    2 45    3 4 5

輸入輸出格式

輸入格式:

一行兩個自然數n、r(1<n<21,1<=r<=n)。

輸出格式:

所有的組合,每一個組合佔一行且其中的元素按由小到大的順序排列,每個元素佔三個字元的位置,所有的組合也按字典順序。
**注意哦!輸出時,每個數字需要3個場寬,pascal可以這樣:
write(ans:3);

輸入輸出範例

輸入範例#1:

5 3

輸出範例#1:

  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

【思路】

  Dfs

  唯一需要注意的就是c++的域寬控制。

 

【代碼】

 

 1 #include<iostream> 2 #include<cstdio> 3 using namespace std; 4  5 const int maxn = 22; 6  7 int A[maxn]; 8 int n,r; 9 10 void dfs(int d,int nowi) {11     if(d==r) {12         for(int i=0;i<r;i++)13           printf("%3d",A[i]);14         printf("\n");15     }16     if(r-d>n-nowi+1) return ;17     for(int i=nowi;i<=n;i++)  {18         A[d]=i;19         dfs(d+1,i+1);20     }21 }22 23 int main() {24     scanf("%d%d",&n,&r);25     dfs(0,1);26     return 0;27 }

 

洛穀P1157 組合的輸出

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.