[Leetcode] Permutations

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);
        }        
      }
    }
}

  1. 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. 
  2. 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. 
  3.  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. 
  4. 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[]. 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值