您的位置:首页 > 其它

Leetcode 46/47 Permutations, Permutations II

2013-02-12 16:32 429 查看
今天做了Leetcode,还挑了一个比较简单的....Permutations

几个注意点:

1.用next permutation做

2.注意swap的时候的下标号

3.注意判断数组是否遍历完毕的时候(70行),判断依据是i<0,而不是i==0,想一想为什么?

(因为数组遍历完还没有找到条件,所以i已经超出了范围!)

4.如果给定的数组有重复元素,这种方法也是可以生成所有的排列的(所以permutaions II也可以过)。

5.72ms Judge Large for Question 46, 168ms Judge Large for Question 47

#include <iostream>
using namespace std;
#include <vector>
#include <algorithm>
//L46 Permutations
//Given a collection of numbers, return all possible permutations.
//
//For example,
//[1,2,3] have the following permutations:
//[1,2,3], [1,3,2], [2,1,3], [2,3,1], [3,1,2], and [3,2,1].

//next permutation method
//we have 123 next is 132 next is 213
//how to find the next permutation?
//we should modify the left as little as possible, so we search from the right.
//find the first element that is ai < a(i+1), that is, there exists one “next permutation”. if not, we are done
//find the smallest larger element than ai from right(ai+1 or the element in the right of it), say aj
//then we swap the ai and aj, so the new “integer” is larger.
//but we will find the “next” permutation, so we should make it smaller
//because currently, the ele in ai+1 is in descending order, so we make it as an ascending order. we just need a transposition.

//edge case: num is empty, or only have 1 element.
class Solution
{
public:
void swap(int *a, int *b)
{
if (a == b)
return;
int temp;
temp = *a;
*a = *b;
*b = temp;
}
vector<vector<int> > permute(vector<int> &num)
{
// Start typing your C/C++ solution below
// DO NOT write int main() function
vector<int> result;
vector<vector<int> > ret;
int len = num.size();
if (num.empty())
return ret;
if (len == 1)
{
ret.push_back(num);
return ret;
}
//sort for all the permutaions
sort(num.begin(), num.end());
int i, j;
while (1)
{
//store the result
ret.push_back(num);
//we find ai < ai+1
for (i = len - 2; i >= 0; i--)
if (num[i] < num[i + 1])
break;
cout << num[0] << "  " << num[1] << " " << num[2] << endl;
//check if there exists the next permutation
if (i < 0 && num[0] >= num[1])
break; //break the while loop, we are done.
//find aj
for (j = len - 1; j >= i + 1; j--)
if (num[j] > num[i])
break;
//swap ai and aj
swap(&num[i], &num[j]);
//transposition from ai+1 to the end
int k;
for (k = i + 1; k <= (i + 1 + (len - 1 - (i + 1)) / 2); k++)
swap(&num[k], &num[len - k + i]);

}
return ret;
}
};

int main()
{
Solution S;
vector<int> arr;
arr.push_back(1);
arr.push_back(2);
arr.push_back(3);
S.permute(arr);
cout << "!!!Hello World!!!" << endl; // prints !!!Hello World!!!
return 0;
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: