1. 程式人生 > >Permutations II -- LeetCode

Permutations II -- LeetCode

分享一下我老師大神的人工智慧教程!零基礎,通俗易懂!http://blog.csdn.net/jiangjunshow

也歡迎大家轉載本篇文章。分享知識,造福人民,實現我們中華民族偉大復興!

                原題連結:  http://oj.leetcode.com/problems/permutations-ii/  
這個題跟 Permutations 非常類似,唯一的區別就是在這個題目中元素集合可以出現重複。這給我們帶來一個問題就是如果不對重複元素加以區別,那麼類似於{1,1,2}這樣的例子我們會有重複結果出現。那麼如何避免這種重複呢?方法就是對於重複的元素迴圈時跳過遞迴函式的呼叫,只對第一個未被使用的進行遞迴,我們那麼這一次結果會出現在第一個的遞迴函式結果中,而後面重復的會被略過。如果第一個重複元素前面的元素還沒在當前結果中,那麼我們不需要進行遞迴。想明白了這一點,程式碼其實很好修改。首先我們要對元素集合排序,從而讓重複元素相鄰,接下來就是一行程式碼對於重複元素和前面元素使用情況的判斷即可。程式碼如下: 
public ArrayList<ArrayList<Integer>> permuteUnique(int[] num) {    ArrayList<ArrayList<Integer>> res = new ArrayList<ArrayList<Integer>>();    if(num==null && num.length==0)        return res;    Arrays.sort(num);    helper(num, new
boolean[num.length], new ArrayList<Integer>(), res);    return res;}private void helper(int[] num, boolean[] used, ArrayList<Integer> item, ArrayList<ArrayList<Integer>> res){    if(item.size() == num.length)    {        res.add(new
ArrayList<Integer>(item));        return;    }    for(int i=0;i<num.length;i++)    {        if(i>0 && !used[i-1] && num[i]==num[i-1]) continue;        if(!used[i])        {            used[i] = true;            item.add(num[i]);            helper(num, used, item, res);            item.remove(item.size()-1);            used[i] = false;        }    }}
這樣的解法是帶有一般性的,把這個程式碼放到 Permutations 中也是正確的,所以如果熟悉的話,面試時如果碰到這個題目建議直接實現這個程式碼,不要假設元素沒有重複,當然可以跟面試官討論,不過一般來說都是要考慮這個情況的哈。
           

給我老師的人工智慧教程打call!http://blog.csdn.net/jiangjunshow

這裡寫圖片描述