• 《算法笔记》8.1小节——搜索专题->深度优先搜索(DFS)


    http://codeup.cn/contest.php

    5972

    这是递归的入门题,求全排列,第一种方法用STL中的函数next_permutation,可以很容易的实现。首先建立好数组,将需要全排列的数字进行初始化,然后调用next_permutation(a,a+n),按照地址进行全排列打印结果.

    #include <stdio.h>
    #include <algorithm>
    using namespace std;
    int a[20];
    int main()
    {
        int n;
        scanf("%d", &n);
        int i;
        for (i = 0; i < n; i++)
        {
            a[i] = i + 1;
        }
        do
        {
            for (i = 0; i < n; i++)
            {
                if (i != n - 1)
                    printf("%d ", a[i]);
                else
                    printf("%d", a[i]);
            }
            printf("
    ");
        } while (next_permutation(a, a + n));
    }

    2.另外一种递归写法如下。

    #include <bits/stdc++.h>
    using namespace std;
    vector<int>ans;
    bool hashTable[20] = { false };//true选false不选
    int i;
    int n;
    void DFS(int index)
    {
        if (index == n)
        {
            for (i = 0; i < n; i++)
            {
                if (i != n - 1)
                    printf("%d ", ans[i]);
                else
                    printf("%d", ans[i]);
            }
            printf("
    ");
            return;
        }
        for (int x = 0; x < n; x++)
        {
            if (hashTable[x] == false)
            {
                ans.push_back(x+1);//选这个元素
                hashTable[x] = true;//将他设置为已选择
                DFS(index + 1);//不选这个元素
                ans.pop_back();//弹出
                hashTable[x] = false;//把这个元素设置为未选择
            }
        }
    }
    int main()
    {
        scanf("%d", &n);
        DFS(0);
    }

    5973

    和这个题很像,求的是组合,也是DFS递归模板的另一版本.

    #include <cstdio>
    #include <vector>
    using namespace std;
    int n, r;
    int a[30];
    vector<int>ans;
    void DFS(int index, int v)
    {
        if (index == n)
        {
            if (v == r)
            {
                vector<int>::iterator it = ans.begin();
                for (; it != ans.end(); it++)
                {
                    if (it != ans.end() - 1)
                    {
                        printf("%d ", *it);
                    }
                    else
                        printf("%d", *it);
                }
                printf("
    ");
            }
            return;
        }
        ans.push_back(a[index]);
        DFS(index + 1, v + 1);
        ans.pop_back();
        DFS(index + 1, v);
    }
    int main()
    {
        scanf("%d %d", &n, &r);
        int i;
        for (i = 0; i < n; i++)
        {
            a[i] = i + 1;
        }
        DFS(0, 0);
    }

      

  • 相关阅读:
    Freezable 对象(WPF)
    排序算法
    属性,构造函数,枚举
    .net 4.0新特性CountDownEvent
    WPF的动画(1)基本动画
    MEF(Managed Extensibility Framework)学习笔记
    WPF依赖属性(续)(4)依赖属性与数据绑定
    [你必须知道的.NET] 第六回:深入浅出关键字base和this
    [你必须知道的.NET] 第三回:历史纠葛:特性和属性
    用命令行部分解决 CNNIC 证书问题
  • 原文地址:https://www.cnblogs.com/legendcong/p/9119487.html
Copyright © 2020-2023  润新知