题目:
LeetCode46 I
Given a collection of distinct numbers, return all possible permutations. (Medium)
For example,[1,2,3]
have the following permutations:
[ [1,2,3], [1,3,2], [2,1,3], [2,3,1], [3,1,2], [3,2,1] ]
LeetCode47 II
Given a collection of numbers that might contain duplicates, return all possible unique permutations.(Medium)
For example,[1,1,2]
have the following unique permutations:
[ [1,1,2], [1,2,1], [2,1,1] ]
分析: 首先先用next_permutation解这两个题。用好STL。
Permutations I:
1 class Solution { 2 public: 3 vector<vector<int>> permute(vector<int>& nums) { 4 vector<vector<int>> result; 5 int len = nums.size(); 6 sort(nums.begin(), nums.end()); 7 do { 8 result.push_back(nums); 9 } while (next_permutation(nums.begin(),nums.end())); 10 11 return result; 12 } 13 };
Permutations II:
1 class Solution { 2 public: 3 vector<vector<int>> permuteUnique(vector<int>& nums) { 4 vector<vector<int>> result; 5 int len = nums.size(); 6 sort(nums.begin(), nums.end()); 7 do { 8 result.push_back(nums); 9 } while (next_permutation(nums.begin(),nums.end())); 10 11 return result; 12 } 13 };
当然,用STL写好的函数肯定不是面试的目的,permutation的递归方法也是经典的回溯算法题。
代码:
1 class Solution { 2 private: 3 vector<vector<int>> result; 4 void helper(vector<int>& nums, int start, int end) { 5 if (start == end) { 6 result.push_back(nums); 7 } 8 for (int i = start; i <= end; ++i) { 9 swap(nums[start], nums[i]); 10 helper(nums, start + 1, end); 11 swap(nums[start], nums[i]); 12 } 13 } 14 public: 15 vector<vector<int>> permute(vector<int>& nums) { 16 helper(nums, 0, nums.size() - 1); 17 return result; 18 } 19 };
时间: 2024-10-15 10:25:15