• 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("%
    ")
    10 #define PF(x) printf("%d ",x)
    11 #define pf(x) printf("%d
    ",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

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

  • 相关阅读:
    Vue23 ref属性
    Vue27 scoped样式
    Vue 24 props
    Vue21 组件
    Vue25 mixin
    Vue29 自定义事件及消息总线
    Vue28 Web Storage
    AcWing2022寒假每日一题(1 月 2 日 ~ 1 月 15 日)
    leetcode 206. Reverse Linked List 反转链表(简单)
    leetcode 647. Palindromic Substrings回文子串(中等)
  • 原文地址:https://www.cnblogs.com/ghostTao/p/4415412.html
Copyright © 2020-2023  润新知