题解 - 取数排列

题目描述

取1到N共N个连续的数字(1≤N≤9),组成每位数不重复的所有可能的N位数,按从小到大的顺序进行编号。当输入一个编号M时,就能打印出与该编号对应的那个N位数。例如,当N=3时,可组成的所有三位数为:

那么,输入编号M=2时,则输出132。

输入

包括两个数,即正整数N(1 <= N <= 9)和正整数M(1 <= M <= 362880)。

输出

只有一行,即与输入的编号M对应的那个N位数。

样例输入

3 2

样例输出 Copy

132

分析

N <= 9,所以可以直接将n全排列,时间复杂度为O(n!),9! = 362880,并且全排列的过程中是从1开始枚举到n,故满足从小到大的关系,即不需要再进行排序,总时间复杂度满足题目要求

全排列

cpp 复制代码
void dfs(int steps){
    if(steps == n + 1){
        tmp++; // tmp记录数量
        for(int i = 1;i <= n;i++) res[tmp][i] = path[i]; // res存储所有满足条件的情况
         
        return ;
    }
  
    for(int i = 1;i <= n;i++){
        if(!st[i]){
            st[i] = true;
            path[steps] = i;
            dfs(steps + 1);
            st[i] = false;
        }
    }
}

代码

cpp 复制代码
#include<bits/stdc++.h>
     
using namespace std;

const int N = 9 + 10,M = 362880 + 10;
 
int n,m;
int path[N];
bool st[N];
int tmp;
int res[M][N];
  
void dfs(int steps){
    if(steps == n + 1){
        tmp++;
        for(int i = 1;i <= n;i++) res[tmp][i] = path[i];
         
        return ;
    }
  
    for(int i = 1;i <= n;i++){
        if(!st[i]){
            st[i] = true;
            path[steps] = i;
            dfs(steps + 1);
            st[i] = false;
        }
    }
}
 
int main(){
    ios::sync_with_stdio;
    cin.tie(0),cout.tie(0);
 
    cin >> n >> m;
 
    dfs(1);
 
    for(int i = 1;i <= n;i++) cout << res[m][i];
 
    return 0;
}
相关推荐
t***54435 分钟前
如何在Dev-C++中使用Clang编译器
开发语言·c++
Qbw20041 小时前
【Linux】进程地址空间
linux·c++
6Hzlia2 小时前
【Hot 100 刷题计划】 LeetCode 739. 每日温度 | C++ 逆序单调栈
c++·算法·leetcode
良木生香2 小时前
【C++初阶】:STL——String从入门到应用完全指南(1)
c语言·开发语言·数据结构·c++·算法
程序员老邢3 小时前
【技术底稿 19】Redis7 集群密码配置 + 权限锁死 + 磁盘占满连锁故障真实排查全记录
java·服务器·经验分享·redis·程序人生·微服务
XWalnut3 小时前
LeetCode刷题 day16
数据结构·算法·leetcode·链表·动态规划
Kurisu_红莉栖3 小时前
c++复习——const,static字
c++
czxyvX4 小时前
1-Qt概述
c++·qt
齐鲁大虾4 小时前
新人编程语言选择指南
javascript·c++·python·c#
CoderMeijun4 小时前
C++ 多线程进阶:Lambda、条件变量与死锁
c++·多线程·条件变量·lambda·死锁·生产者消费者