字典序排列- STL next_permutation、DFS(深度优先搜索)

11 篇文章 0 订阅

擅长排列的小明

时间限制: 1000 ms  |  内存限制: 65535 KB
难度: 4
描述
小明十分聪明,而且十分擅长排列计算。比如给小明一个数字5,他能立刻给出1-5按字典序的全排列,如果你想为难他,在这5个数字中选出几个数字让他继续全排列,那么你就错了,他同样的很擅长。现在需要你写一个程序来验证擅长排列的小明到底对不对。
输入
第一行输入整数N(1<N<10)表示多少组测试数据,
每组测试数据第一行两个整数 n m (1<n<9,0<m<=n)
输出
在1-n中选取m个字符进行全排列,按字典序全部输出,每种排列占一行,每组数据间不需分界。如样例
样例输入
2
3 1
4 2
样例输出
1
2
3
12
13
14
21
23
24
31
32
34
41
42

43

解题思路1:  用next_permutation 函数得  1.。。n的 全排列  

缺点:性能受n 控制 较浪费

//
//  main.cpp
//  NYOJ-19 擅长排列的小明
//
//  Created by H@L on 14-6-30.
//  Copyright (c) 2014年 Hzw. All rights reserved.
//


#include<iostream>
#include <vector>
#include <algorithm>
#include <string>
using namespace std;

string str = "123456789";
int main()
{
    int N;
	cin>>N;
    while (N--) {
        int n,m;
        string str1,strLast;
        cin >> n >> m;
        do{
            str1 = str.substr(0,m);
            if (str1 != strLast)
            {
                cout << str1 << endl;
                strLast = str1;
            }
        }while (next_permutation(str.begin(),str.begin()+n));
        
    }
    return 0;
}

解题思路二:把元素都是当一个顶点 然后根据DFS(深度优先搜索遍历算法)遍历访问各个顶点 得出排列

//
//  main.cpp
//  NYOJ-19 擅长排列的小明
//  DFS 深度优先搜索
//  Created by H@L on 14-6-30.
//  Copyright (c) 2014年 Hzw. All rights reserved.
//


#include<iostream>
#include "string.h"

using namespace std;

int num[10] = {0};
char strOut[10] ={0};

void DFS_f(int iNum,int depth,int iCount)
{
    if (depth == 0) {
        cout << strOut << endl;
        return ;
    }
    for (int i=1; i <= iNum; i++) {
        if (num[i] != 1) {
            num[i] = 1;
            strOut[iCount++] = '0'+i;
            DFS_f(iNum,depth-1,iCount);
            iCount--;
            num[i] = 0;
        }
    }
    return;
}
int main()
{
    int N;
	cin>>N;
    while (N--) {
        int n,m;
        memset(strOut, 0, sizeof(strOut));
        cin >> n >> m;
        DFS_f(n, m, 0);
    }
    return 0;
}


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值