Next Permutation 求下一个排序@LeetCode
来源:互联网 发布:数据库打不开sql文件 编辑:程序博客网 时间:2024/05/02 11:17
完全没有思路,参考了 http://www.cnblogs.com/etcow/archive/2012/10/02/2710083.html
分三步:
1. 从后往前找falling edge,下降沿。(下降之后的那个元素)
2. 从下降沿开始往后找出替换它的元素。(就是第一个比它小的前一个元素)
3. 反转后面所有元素,让他从小到大sorted(因为之前是从大到小sorted的)
例如 “547532“
1. “547532”, 4是下降沿。
2. “547532”, 5是要替换的元素, 替换后得到 “ 557432”
3. "557432", 7432反转,得到 “552347”。
package Level4;/** * 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,23,2,1 → 1,2,31,1,5 → 1,5,1 * */public class S31 {public static void main(String[] args) {}public void nextPermutation(int[] num) { if(num.length <= 1){ return; } // 1. 从后往前找falling edge,下降沿。(下降之后的那个元素) int edge = -1; for(int i=num.length-2; i>=0; i--){ if(num[i] < num[i+1]){ edge = i; break; } } if(edge > -1){ // 2. 从下降沿开始往后找出替换它的元素。(就是第一个比它小的前一个元素) for(int i=edge+1; i<num.length; i++){ if(num[edge] >= num[i]){ nextPermutationSwap(num, edge, i-1); break; } if(i == num.length-1){ nextPermutationSwap(num, edge, i); break; } } } // 3. 反转后面所有元素,让他从小到大sorted(因为之前是从大到小sorted的) for(int i=edge+1, j=num.length-1; i<=edge+(num.length-edge-1)/2; i++, j--){ nextPermutationSwap(num, i, j); } }public void nextPermutationSwap(int[] num, int i, int j){int tmp = num[i];num[i] = num[j];num[j] = tmp;}}
- Next Permutation 求下一个排序@LeetCode
- LeetCode[31] Next Permutation 求下一个排列
- leetcode:Next Permutation (求下一个排列) 【面试算法题】
- Next Permutation-leetcode下一个排列组合
- LeetCode Next Permutation 生成下一个序列
- Next Permutation -- LeetCode(下一个字典序)
- LeetCode | Next Permutation(下一个排列)
- LeetCode 31 Next Permutation(下一个排列)
- [LeetCode]Next Permutation下一个排列问题
- LeetCode 31. Next Permutation(下一个排列)
- LeetCode 31 Next Permutation (下一个排列)
- leetcode:31. Next Permutation 下一个排列
- leetCode 31.Next Permutation (下一个字典序排序) 解题思路和方法
- 下一个排列(Next Permutation)
- Next Permutation 下一个排列
- Next Permutation 下一个排列
- LeetCode OJ 之 Next Permutation(下一个排列)
- leetcode-31 Next Permutation 数字排列组合找到下一个更大值
- Entity Framework 对多次数据库连接保持事务一致性
- 我读过的最好的epoll讲解
- GDI-贝塞尔曲线 的例子
- 1.easyui+ztree案例:下载及介绍
- Ubuntu使用过程中的一些疑难杂症解决
- Next Permutation 求下一个排序@LeetCode
- EditText
- 自己补充的知识点清单
- 饭局中的智慧
- DG - 逻辑standby角色转换
- 九度题目:还是约瑟夫环(1189)
- 主流手机游戏引擎介绍
- 2.easyui+ztree案例:在项目中引入easyui
- stm32f10x ucosii 移植要点