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
, instead ofoutput.add((ArrayList<Integer>)al.clone());
But I just cannot complier this phrase in any way. "unsafe operation" or "cannot find symbol" errors pop out.List<Integer> bl = new ArrayList<Integer> (al); output.add(bl);
- The way stating bl is very important.
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.List<Integer> bl = new ArrayList<Integer> (); bl = al; output.add(bl);
- 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[].