標籤:全排列 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||