Leetcode 46. Permutations
给定一个包含不同整数的集合,生成所有可能的排列。
class Solution { public: vector<vector<int>> permute(vector<int>& nums) { vector<vector<int>> result; help(nums, 0, result); return result; } // permute num[begin..end] // invariant: num[0..begin-1] have been fixed/permuted void help(vector<int>& nums, int begin, vector<vector<int>>& result){ if(begin >= nums.size()){ // one permutation instance result.push_back(nums); return; } for(int i = begin; i < nums.size(); ++i){ swap(nums[i], nums[begin]); help(nums, begin + 1, result); // reset swap(nums[i], nums[begin]); } } };
Leetcode 47. Permutations II
给定一个可能包含重复整数的集合,生成所有可能的排列。
分析:值传递?
class Solution { public: vector<vector<int>> permuteUnique(vector<int>& nums) { vector<vector<int>> result; sort(nums.begin(), nums.end()); help(nums, 0, result); return result; } void help(vector<int> nums, int begin, vector<vector<int>>& result){ if(begin == nums.size() - 1){ result.push_back(nums); return; } for(int i = begin; i < nums.size(); ++i){ if(i != begin && nums[i] == nums[begin]) continue; else{ swap(nums[begin], nums[i]); help(nums, begin + 1, result); } } } };
Leetcode 31. Next Permutation
实现next permutation
class Solution { public: void nextPermutation(vector<int>& nums) { int n = nums.size(), k, l; for(k = n - 2; k >= 0; --k){ if(nums[k] < nums[k + 1]) break; } if(k < 0) reverse(nums.begin(), nums.end()); else{ for(l = n - 1; l > k; --l){ if(nums[l] > nums[k]) break; } swap(nums[k], nums[l]); reverse(nums.begin() + k + 1, nums.end()); } } };
Leetcode 60. Permutation Sequence
集合$[1,2,3,...,n]$可以构成$n!$个排列。给定$n,k$,求第k个排列(index from 1).
分析:每一个数字开头的排列共有$(n - 1)!$个,确定第k个在哪一组,把那个数字放到s[0]上,然后同样的方法确定s[1...n-1].
class Solution { public: string getPermutation(int n, int k) { int i, j, f = 1; // left part of s is partially formed permutation, right part is the leftover chars. string s(n, '0'); for(int i = 1; i <= n; ++i){ f *= i; s[i - 1] += i; // make s become 1234...n } for(i = 0, k--; i < n; ++i){ f /= n - i; j = i + k / f; // calculate index of char to put at s[i] char c = s[j]; // remove c by shifting to cover up (adjust the right part). for(; j > i; --j) s[j] = s[j - 1]; k %= f; s[i] = c; } return s; } };