标签:侯捷 源码 algorithm leetcode 面试题
Given a collection of numbers that might contain duplicates, return all possible unique permutations.
For example,
[1,1,2]
have the following unique permutations:
[1,1,2]
, [1,2,1]
,
and [2,1,1]
.
bool nextPermutetion(vector<int> &num) { int i = num.size() - 1; while (i >= 1) { if(num[i] > num[i - 1]) { --i; int ii = num.size() - 1; while (ii > i && num[ii] <= num[i]) --ii; if(ii > i) { swap(num[i], num[ii]); reverse(num.begin() + i + 1, num.end()); return true; } } else --i; } if(i == 0) return false; return true; } vector<vector<int> > permuteUnique(vector<int> &num) { vector<vector<int> > re; if(num.size() == 0) return re; sort(num.begin(), num.end()); re.push_back(num); while (nextPermutetion(num)) { re.push_back(num); } return re; }//code 2
vector<vector<int> > permuteUnique(vector<int> &num) { vector<vector<int> > re; if(num.size() == 0) return re; sort(num.begin(), num.end()); re.push_back(num); int i = num.size() - 1; while(1){ int ii = i; --i; if(i < 0) return re; if(num[ii] > num[i]) { ii = num.size() - 1; while (ii > i && num[ii] <= num[i]) --ii; if(ii > i) { swap(num[i], num[ii]); reverse(num.begin() + i + 1, num.end()); re.push_back(num); i = num.size() - 1; } } }//end while 1 return re; }
【leetcode】Permutations II,布布扣,bubuko.com
标签:侯捷 源码 algorithm leetcode 面试题
原文地址:http://blog.csdn.net/shiquxinkong/article/details/27868007