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

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

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

 

搞清排列过程!

字典序排列

把升序的排列(当然,也可以实现为降序)作为当前排列开始,然后依次计算当前排列的下一个字典序排列。

对当前排列从后向前扫描,找到一对为升序的相邻元素,记为i和j(i < j)。如果不存在这样一对为升序的相邻元素,则所有排列均已找到,算法结束;否则,重新对当前排列从后向前扫描,找到第一个大于i的元素k,交换i和k,然后对从j开始到结束的子序列反转,则此时得到的新排列就为下一个字典序排列。这种方式实现得到的所有排列是按字典序有序的,这也是C++ STL算法next_permutation的思想。

1 class Solution { 2 public: 3     void nextPermutation(vector
&num) { 4 if (num.size() < 2) return; 5 int i, k; 6 for (i = num.size() - 2; i >= 0; --i) if (num[i] < num[i+1]) break; 7 for (k = num.size() - 1; k > i; --k) if (num[i] < num[k]) break; 8 if (i >= 0) swap(num[i], num[k]); 9 reverse(num.begin() + i + 1, num.end());10 }11 };

 

如果是找全排列的话,就可以给next_permutation加一个返回值来标记还有没有下一个permutation了,如果没有就反回false。

1 class Solution { 2 public: 3     bool nextPermute(vector
&num) { 4 if (num.size() < 2) return false; 5 int i, k; 6 for (i = num.size() - 2; i >= 0; --i) if (num[i] < num[i+1]) break; 7 for (k = num.size() - 1; k > i; --k) if (num[i] < num[k]) break; 8 if (i >= 0) swap(num[i], num[k]); 9 reverse(num.begin() + i + 1, num.end());10 return i >= 0;11 }12 13 vector
> permute(vector
&num) {14 vector
> res;15 sort(num.begin(), num.end());16 do {17 res.push_back(num);18 } while (nextPermute(num));19 return res;20 }21 };

 

当然也可以用DFS来做,但是有重复元素的话DFS就有点无能为力了。

1 class Solution { 2 public: 3     void dfs(vector
> &res, vector
&path, vector
&num, int idx) { 4 if (idx == num.size()) { 5 res.push_back(path); 6 return; 7 } 8 for (auto v : num) if (find(path.begin(), path.end(), v) == path.end()) { 9 path.push_back(v);10 dfs(res, path, num, idx + 1);11 path.pop_back();12 }13 }14 15 vector
> permute(vector
&num) {16 vector
> res;17 vector
path;18 dfs(res, path, num, 0);19 return res;20 }21 };

 

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

你可能感兴趣的文章
JS异步的几种写法
查看>>
nodejs: mac上阿里云部署
查看>>
680 Valid Palindrome II
查看>>
「金三银四」| 手撕排序算法(JavaScript 实现)(上)
查看>>
如何理解自动化测试数据驱动与关键字驱动的区别?
查看>>
设计模式之-代理模式
查看>>
Fragment
查看>>
一个五年架构师凭什么基本年薪酬就可以达到50万
查看>>
npm进阶
查看>>
[译] 僵尸币时代即将到来?
查看>>
Java设计模式之单例模式(几种写法及比较)
查看>>
总结:44个Python3字符串内置方法大全及示例
查看>>
2018年最值得关注的30个Vue开源项目
查看>>
docker之DockerSwarm的了解
查看>>
大区块的BCH给智能合约更大的发展潜力
查看>>
springcloud(五):熔断监控Hystrix Dashboard
查看>>
七年软件测试历程,回过头来,最能帮助我的还是这些.....
查看>>
yum 安装nginx
查看>>
前端(js+JQuery非空校验)
查看>>
[Android] ImageView.ScaleType设置图解
查看>>