博客
关于我
强烈建议你试试无所不能的chatGPT,快点击我
31. Next Permutation
阅读量:7131 次
发布时间:2019-06-28

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

31. Next Permutation

Implement next permutation, which rearranges numbers into the lexicographically next greater permutation of numbers.

If such arrangement is not possible, it must rearrange it as the lowest possible order (ie, sorted in ascending order).

The replacement must be in-place, do not allocate extra memory.

Here are some examples. Inputs are in the left-hand column and its corresponding outputs are in the right-hand column.

1,2,3 → 1,3,2
3,2,1 → 1,2,3
1,1,5 → 1,5,1

最简单的方式就是先全排列了,再去匹配就行~  而全排列也是典型的DFS

var a = [1,2,3,4,5];var res = [];function swap(a,i,j){ var temp = a[i];  a[i] = a[j];  a[j] = temp;}function pl(a,start,res){       a = a.slice();     if(start>=a.length){          res.push(a);      }     for(var i = start;i

 

其实这个问题本身是有固定套路的,直接背住下面步骤即可:

 

Now let's pick a number, for example, 24387651.

what is the next permutation? 24513678.

How can I get the answer?

First step: find the first ascending digit from the back of the number. 3 < 8 > 7 > 6 > 5 > 1. Then 3 is the digit.

Second step: swap that digit with the next big digit in following digits. Which one is the next big digit in 87651? 5! So swap them. Now the number becomes 24587631.

Third step: sort 87631 into 13678. The final answer is 24513678.

 

1 /** 2  * @param {number[]} nums 3  * @return {void} Do not return anything, modify nums in-place instead. 4  */ 5 var nextPermutation = function(num) { 6      7       for(var i = num.length - 2; i >= 0; i--){ 8         if(num[i] < num[i + 1]){ 9             var pos;10             var diff = Math.pow(2,31)-1;11             for( j = i + 1; j < num.length; j++){12                 if(num[j] > num[i] && Math.abs(num[i] - num[j]) <= diff){13                     diff = Math.abs(num[i] - num[j]);14                     pos = j;15                 }16             }17             18             var temp = num[i];19             num[i] = num[pos];20             num[pos] = temp;21        22             23             for(var k =i+1,q=num.length -1;k

 

转载于:https://www.cnblogs.com/huenchao/p/7701241.html

你可能感兴趣的文章
CCIE职业发展系列典型案列分析之RIPv1协议配置的解决方案
查看>>
【高德地图API】如何制作自己的旅游地图?
查看>>
windbg 通过网络联机调试配置
查看>>
iOS 瘦身之道
查看>>
nodejs的配置
查看>>
centos7下集群部署zookeeper(伪集群)
查看>>
mysql主从复制
查看>>
IT168:2014年APT***发展趋势及防御策略调研
查看>>
用好ul和li
查看>>
基于JQUERY的AJAX跨域问题完美解决方案
查看>>
搭建LVS+Keepalived高可用负载均衡集群
查看>>
局域网PING不通原因是什么?解决ping不通局域网电脑
查看>>
泄露们事件
查看>>
springmvc提交带日期的表单400
查看>>
我的友情链接
查看>>
使用Python socket获取本机ip
查看>>
java 简单的加解密操作
查看>>
qmake 之 CONFIG 与 QT 乱谈
查看>>
ExtJS 创建动态加载树
查看>>
我的友情链接
查看>>