leetcode46. Permutations 、47. Permutations II、 剑指offer字符串的排列
字符串排列和PermutationsII差不多
Permutations第一种解法:
这种方法从0开始遍历,通过visited来存储是否被访问到,level代表每次已经存储了多少个数字
时间复杂度O(n!)
class Solution { public: vector<vector<int>> permute(vector<int>& nums) { vector<vector<int> > result; if(nums.empty()) return result; vector<int> res; vector<bool> visited(nums.size(),0); int level = 0; permute(nums,result,res,visited,level); return result; } void permute(vector<int>& nums,vector<vector<int> >& result,vector<int>& res,vector<bool>& visited,int level){ if(level == nums.size()){ result.push_back(res);
return;
} for(int i = 0;i < nums.size();i++){ if(visited[i] == 1) continue; res.push_back(nums[i]); visited[i] = 1; permute(nums,result,res,visited,level+1); res.pop_back(); visited[i] = 0; } } };
第二种解法:
class Solution { public: vector<vector<int>> permute(vector<int>& nums) { permute(nums,0); return res; } void permute(vector<int>& nums,int begin){ if(begin == nums.size() - 1) res.push_back(nums); for(int i = begin;i < nums.size();i++){ swap(nums[i],nums[begin]); permute(nums,begin+1); swap(nums[i],nums[begin]); } } vector<vector<int>> res; };
Permutations II
class Solution { public: vector<vector<int>> permuteUnique(vector<int>& nums) { vector<vector<int> > result; if(nums.empty()) return result; vector<int> res; vector<bool> visited(nums.size(),0); int level = 0; sort(nums.begin(),nums.end()); permute(nums,result,res,visited,level); return result; } void permute(vector<int>& nums,vector<vector<int> >& result,vector<int>& res,vector<bool>& visited,int level){ if(level == nums.size()){ result.push_back(res);
return;
} for(int i = 0;i < nums.size();i++){ if(visited[i] == 1) continue; if(i > 0 && nums[i] == nums[i-1] && visited[i-1] == 1) continue; visited[i] = 1; res.push_back(nums[i]); permute(nums,result,res,visited,level+1); res.pop_back(); visited[i] = 0; } } };
把第二个剪枝写在for循环一开始这种方式,实际上每次只存储重复数字中的第二个,相当于按照逆序的方式存储相同的数字