[LeetCode] Permutations II

來源:互聯網
上載者:User

標籤: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!

 

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.