您的位置:首页 > 编程语言 > Java开发

[Leetcode] Permutations

2014-08-14 23:47 232 查看
Given a collection of numbers, return all possible permutations.

public class Solution {

boolean [] isUsed;
int numLength;
ArrayList<List<Integer>> output;
ArrayList <Integer> al;

public List<List<Integer>> permute(int[] num) {
numLength = num.length;
al = new ArrayList <Integer> ();
output = new ArrayList<List<Integer>>();
isUsed = new boolean[num.length];
doPermutation(0, num);
return output;
}

private void doPermutation(int index, int[] num){
if(index == numLength){
List<Integer> bl = new ArrayList<Integer> (al); output.add(bl);
return;
}
for (int i = 0; i < numLength; i++) {
if(isUsed[i] == false){
al.add(num[i]);
isUsed[i] = true;
doPermutation(index+1, num);
isUsed[i] = false;
al.remove(index);
}
}
}
}
In the original code, the coder use
output.add((ArrayList<Integer>)al.clone());
, instead of  
List<Integer> bl = new ArrayList<Integer>  (al);
output.add(bl);
But I just cannot complier this phrase in any way. "unsafe operation" or "cannot find symbol" errors pop out. 
The way stating bl is very important. 
List<Integer> bl = new ArrayList<Integer>  ();
bl = al;
output.add(bl);
This makes
no sense if you're trying to pass BY VALUE. Cause it's NOT copying the whole value in al to bl, but only copies the reference to bl. It means, now both al and bl point to the same physic storage. So any operations to bl is the same to al. 
 The third question is that why we need the value of al instead of reference. The result of printing output after add (bl)
shows that the right values have been stored in output list. Because there are remove operations after adding, if it is the reference that passing to output, then once the member in al is removed, then al in output would be changed simultaneously. IT IS NOT
BECAUSE OUTPUT DOSE NOT STORE THE VALUE, BUT THE CHANGES IN AL WILL ALSO HAPPEN IN OUTPUT. 
The flow diagram is showed below. Index counts the number of current member in al. So every time remove(index) will remove
the last object in al.  i is used to find the possible member in number[]. 
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  java leetcode iteration