博客
关于我
强烈建议你试试无所不能的chatGPT,快点击我
[LeetCode] Permutation Sequence
阅读量:6655 次
发布时间:2019-06-25

本文共 1363 字,大约阅读时间需要 4 分钟。

The set [1,2,3,…,n] contains a total of n! unique permutations.

By listing and labeling all of the permutations in order,

We get the following sequence (ie, for n = 3):

  1. "123"
  2. "132"
  3. "213"
  4. "231"
  5. "312"
  6. "321"

 

Given n and k, return the kth permutation sequence.

Note: Given n will be between 1 and 9 inclusive.

DFS从小到大枚举排列,到K时输出。

1 class Solution { 2 private: 3     int a[10]; 4     bool canUse[10]; 5     string ret; 6 public: 7     void dfs(int dep, int maxDep, int &k) 8     { 9         if (k == 0)10             return;11             12         if (dep == maxDep)13         {14             k--;15             if (k == 0)16             {17                 ret = "";18                 for(int i = 0; i < maxDep; i++)19                     ret += (char)(a[i] + '0');20                 return;21             }22         }23         24         for(int i = 1; i <= maxDep; i++)25             if (canUse[i])26             {27                 canUse[i] = false;28                 a[dep] = i;29                 dfs(dep + 1, maxDep, k);30                 canUse[i] = true;31             }32     }33     34     string getPermutation(int n, int k) {35         // Start typing your C/C++ solution below36         // DO NOT write int main() function37         memset(canUse, true, sizeof(canUse));38         39         dfs(0, n, k);40         41         return ret;42     }43 };

转载地址:http://ozjto.baihongyu.com/

你可能感兴趣的文章
MongoDB 下载 安装 启动
查看>>
我的友情链接
查看>>
【小松教你手游开发】【unity实用技能】unity ios快捷打包
查看>>
golang 使用时间通过md5生成token
查看>>
caffe编译的问题解决:“cublas_v2.h: No such file or directory”
查看>>
40岁后才明白的道理:人一生奋斗余地很有限
查看>>
正则符号整理
查看>>
Asp.net core 二级域名的设置
查看>>
es 字段 replace
查看>>
Oracle Study之案例--延迟块清除(deferred block cleanout)
查看>>
【LAMP】03、构建分离式的LAMP
查看>>
大快DKhadoop大数据处理平台详解
查看>>
Android卡顿优化:卡顿分析方法
查看>>
人生若只如初见
查看>>
Ext4.1中文API文档已经全部翻译完成!
查看>>
linux下tomcat 管理端无法进入
查看>>
接口在ADO.NET中使用方法
查看>>
会做人比会写程序更重要
查看>>
Python生成简单分形
查看>>
开源一套数据异地备份系统
查看>>