diff --git a/Permutations.h b/Permutations.h index 3a34865..40856dd 100644 --- a/Permutations.h +++ b/Permutations.h @@ -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 { @@ -46,3 +50,35 @@ class Solution { } } }; + +class Solution2 { +public: + //return all possible unique permutations. + vector> permute(vector& nums) { + sort(nums.begin(), nums.end());//!!! + vector> 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; + } +}; \ No newline at end of file diff --git a/PermutationsII.h b/PermutationsII.h index dbea526..898d23d 100644 --- a/PermutationsII.h +++ b/PermutationsII.h @@ -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 { @@ -49,3 +52,35 @@ class Solution { } } }; + +class Solution2 { +public: + //return all possible unique permutations. + vector> permuteUnique(vector& nums) { + sort(nums.begin(), nums.end());//!!! + vector> 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; + } +}; \ No newline at end of file