Permutations Permutations||

來源:互聯網
上載者:User

標籤:全排列   permutations   leetcode   

地址:https://oj.leetcode.com/problems/permutations/ 

https://oj.leetcode.com/problems/permutations-ii/

題目簡單說就是實現全排列。為了實現這個要求首先進行一下觀察。

用123來樣本下。123的全排列有123、132、213、231、312、321這六種。首先考慮213和321這二個數是如何得出的。顯然這二個都是123中的1與後面兩數交換得到的。然後可以將123的第二個數和每三個數交換得到132。同理可以根據213和321來得231和312。因此可以知道——全排列就是從第一個數字起每個數分別與它後面的數字交換。

題目Permutations||要求能處理有重複元素的全排列。觀察對122,第一個數1與第二個數2交換得到212,然後考慮第一個數1與第三個數2交換,此時由於第三個數等於第二個數,所以第一個數不再與第三個數交換。再考慮212,它的第二個數與第三個數交換可以得到解決221。此時全排列產生完畢。全排列中去掉重複的規則——去重的全排列就是從第一個數字起每個數分別與它後面非重複出現的數字交換。用編程的話描述就是第i個數與第j個數交換時,要求[i,j)中沒有與第j個數相等的數。

下面是Permutations||代碼,其實Permutations|| 代碼直接改掉那個方法名稱提交肯定可以通過。因為Permutations||是考慮了重複元素,而Permutations不需要考慮有重複元素出現。

public class Solution {    public List<List<Integer>> permuteUnique(int[] num) {List<List<Integer>> ans = new ArrayList<List<Integer>>();AllRange(num, 0, num.length-1, ans);return ans;}public void AllRange(int[]num,int start,int end,List<List<Integer>> ans){// 某個全排列完成添加if(start == end){List<Integer> temp = new ArrayList<Integer>();for(int i=0;i<num.length;i++){temp.add(num[i]);}ans.add(temp);}// 分別與後面元素進行交換for(int i=start;i<=end;i++){if(IsSwap(num, start, i)){SwapTwoNum(num, start, i);AllRange(num, start+1, end, ans);SwapTwoNum(num, start, i);}}}public void SwapTwoNum(int[]num,int x,int y){int temp = num[x];num[x] = num[y];num[y] = temp;}// 判斷是否可以進行交換boolean IsSwap(int[]num,int start,int end){for(int i=start;i<end;i++){if(num[i]==num[end]){return false;}}return true;}}

Permutations Permutations||

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在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.