Skip to content

another solution #22

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Open
wants to merge 2 commits into
base: master
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
36 changes: 36 additions & 0 deletions Permutations.h
Original file line number Diff line number Diff line change
Expand Up @@ -12,6 +12,10 @@
[1,2,3], [1,3,2], [2,1,3], [2,3,1], [3,1,2], and [3,2,1].

Solution: dfs...
Solution2:non-recursive and unique result. Find the next permutation and add it to result set,
this will miss permutations that 'smaller' than the given 'nums'.
So, at first,we sort the nums. This is the fastest one in all test case. the dfs's
result may contain duplicate permutations.
*/

class Solution {
Expand Down Expand Up @@ -46,3 +50,35 @@ class Solution {
}
}
};

class Solution2 {
public:
//return all possible unique permutations.
vector<vector<int>> permute(vector<int>& nums) {
sort(nums.begin(), nums.end());//!!!
vector<vector<int>> ret;
ret.push_back(nums);
while (1)
{
int idx = -1;
for (int i = nums.size() - 1; i > 0; i--){
if (nums[i] > nums[i - 1]){
idx = i - 1;
break;
}
}
if (idx == -1) break;
for (int i = nums.size() - 1; i > 0; i--){
if (nums[i] > nums[idx]){
int tmp = nums[i];
nums[i] = nums[idx];
nums[idx] = tmp;
break;
}
}
sort(&nums[0] + idx + 1, &nums[0] + nums.size());
ret.push_back(nums);
}
return ret;
}
};
35 changes: 35 additions & 0 deletions PermutationsII.h
Original file line number Diff line number Diff line change
Expand Up @@ -12,6 +12,9 @@
[1,1,2], [1,2,1], and [2,1,1].

Solution: dfs...
Solution2:non-recursive. Find the next permutation and add it to result set,
this will miss permutations that 'smaller' than the given 'nums'.
So, at first,we sort the nums. This is the fastest one in all test case.
*/

class Solution {
Expand Down Expand Up @@ -49,3 +52,35 @@ class Solution {
}
}
};

class Solution2 {
public:
//return all possible unique permutations.
vector<vector<int>> permuteUnique(vector<int>& nums) {
sort(nums.begin(), nums.end());//!!!
vector<vector<int>> ret;
ret.push_back(nums);
while (1)
{
int idx = -1;
for (int i = nums.size() - 1; i > 0; i--){
if (nums[i] > nums[i - 1]){
idx = i - 1;
break;
}
}
if (idx == -1) break;
for (int i = nums.size() - 1; i > 0; i--){
if (nums[i] > nums[idx]){
int tmp = nums[i];
nums[i] = nums[idx];
nums[idx] = tmp;
break;
}
}
sort(&nums[0] + idx + 1, &nums[0] + nums.size());
ret.push_back(nums);
}
return ret;
}
};