vector<vector<int>> permuteUnique(vector<int>& nums) { sort(nums.begin(), nums.end()); vector<vector<int>> res; vector<int> perm; permuteUniqueHelper(res, nums, perm); return res; }
vector<vector<int> > permuteUniqueSub(vector<int> &num) { sort(num.begin(),num.end());//sort the original array. vector<bool> used(num.size(),false); vector<int> subans; vector<vector<int>> ans; permuteUniqueHelper(num,subans,used,ans); return ans; }
/** * @param nums: A list of integers. * @return: A list of unique permutations. */ vector<vector<int>> permuteUnique(vector<int> &nums) { vector<vector<int>> result; vector<bool> used(nums.size(), false); vector<int> ans; sort(nums.begin(), nums.end()); permuteUniqueHelper(nums, &used, &ans, &result); return result; }
void permuteUniqueHelper(vector<int> &num,vector<int> & subans,vector<bool> &used, vector<vector<int>> & ans){ if (subans.size() == num.size()) { ans.push_back(subans); return; } for (int i = 0; i < num.size(); i++) { if (used[i] || (i != 0 && num[i] == num[i - 1] && used[i - 1])) continue; used[i] = true; subans.push_back(num[i]); permuteUniqueHelper(num,subans,used,ans); used[i] = false; subans.pop_back(); } }
void permuteUniqueHelper(vector<vector<int>>& res, vector<int>& nums, vector<int>& perm) { if(nums.empty()) { res.push_back(perm); } for(int i = 0; i < nums.size(); i++) { if(i > 0 && nums[i] == nums[i - 1]) { continue; } perm.push_back(nums[i]); nums.erase(nums.begin() + i); permuteUniqueHelper(res, nums, perm); nums.insert(nums.begin() + i, perm.back()); perm.pop_back(); } }
void permuteUniqueHelper(const vector<int> &A, vector<bool> *used, vector<int> *ans, vector<vector<int>> *result) { if (ans->size() == A.size()) { result->emplace_back(*ans); return; } for (size_t i = 0; i < A.size(); ++i) { if ((*used)[i] || (i != 0 && A[i - 1] == A[i] && !(*used)[i - 1])) { continue; } (*used)[i] = true; ans->emplace_back(A[i]); permuteUniqueHelper(A, used, ans, result); ans->pop_back(); (*used)[i] = false; } }
vector<vector<int>> SubSetTest::permuteUnique( const vector<int>& num ) { vector<vector<int>> rst; if (num.size() == 0) { return rst; } vector<int> list; vector<int> visited; visited.insert(visited.begin(), num.size(), 0); vector<int> tmpNum = num; //attention: const can't be modified sort(tmpNum.begin(),tmpNum.end(),less<int>()); //attention: ascending greater<int>() descending permuteUniqueHelper(rst, list, visited, num); return rst; }
void SubSetTest::permuteUniqueHelper( vector<vector<int>>& rst, vector<int>& list, vector<int>& visited, const vector<int>& num ) { if (list.size() == num.size()) { rst.push_back(list); return; //attention } for (int i = 0; i < num.size(); ++i) { if (visited[i] == 1 || (i != 0 && num[i] == num[i - 1] && visited[i - 1] == 0)){ continue; } visited[i] = 1; list.push_back(num[i]); permuteUniqueHelper(rst, list, visited, num); list.pop_back(); visited[i] = 0; //visited[visited.size() - 1] = 0; //attention: wrong } }