標籤:style blog color os io for ar cti
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].
這道題很容易出現Time Limit Exceeded!
分析:
輸入:[1,1,0,0,1,-1,-1,1],將會有650條答案,但分析一下這裡面一開始就有很多重複的,所以對於bfs的思想在求解的過程中要去掉多餘的基數,後面才會少費時間。
方法1:把下標存到te中,然後變回本身的數字Time Limit Exceeded!
class Solution {public: vector<vector<int> > permuteUnique(vector<int> &num) { vector<vector<int> > result,temp2; int len = num.size(); //先給tempRes裡存num的下標 vector<int> te,temp; for(int i=0;i<len;i++){ if(find(temp.begin(),temp.end(),num[i])==temp.end()){ temp.push_back(num[i]); te.push_back(i); temp2.push_back(te); te.clear(); } }//end for while(!temp2.empty()){ te = temp2.back(); temp2.pop_back(); if(te.size() == len){ for(int i=0;i<len;i++){ te[i] = num[te[i]]; } if(find(result.begin(),result.end(),te)==result.end()) result.push_back(te); continue; } for(int i=0;i<len;i++){ if(find(te.begin(),te.end(),i)==te.end()){ te.push_back(i); temp2.push_back(te); te.pop_back(); } } }//end while return result; }};
方法2:與上面方法一模一樣,只不過求解過程中把多餘的vector及時去掉了。Accept!