leetcode:Next Permutation

原文地址:http://www.cnblogs.com/easonliu/p/3632442.html

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<int> &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<int> &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<vector<int> > permute(vector<int> &num) {
14         vector<vector<int>> 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<vector<int>> &res, vector<int> &path, vector<int> &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<vector<int> > permute(vector<int> &num) {
16         vector<vector<int>> res;
17         vector<int> path;
18         dfs(res, path, num, 0);
19         return res;
20     }
21 };
复制代码
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值