题解 - 取数排列

题目描述

取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;
}
相关推荐
geovindu4 小时前
python:DecisionTree
开发语言·后端·python·算法
ShineWinsu4 小时前
对于Qt:事件的解析
c++·qt·面试·笔试·gui·客户端·事件
geovindu5 小时前
python: Decision Tree Regressor
开发语言·后端·python·算法·决策树
闻缺陷则喜何志丹6 小时前
【数论】P10136 [USACO24JAN] Cowlendar S|普及+
c++·数学·数论·洛谷
apcipot_rain7 小时前
某游戏公司C++游开实习 机试复盘
c++·游戏
AllData公司负责人8 小时前
实战二:AllData大模型与AI数据底座-数据传输平台-DBSyncer,搭建 Http 接口同步至 Doris,API 业务数据自动拉取入数仓
大数据·数据库·数据仓库·人工智能·算法·http·doris
武子康8 小时前
火系被选七成,就应该削弱吗?
人工智能·算法·机器学习
炸膛坦客9 小时前
单片机/C/C++八股:(三十七)指针数组 和 数组指针
c语言·开发语言·c++
夜不会漫长9 小时前
C++:C++11特性
开发语言·c++·算法