Permutations

Given a collection of distinct numbers, return all possible permutations.

For example,
[1,2,3]have the following permutations:

[
  [1,2,3],
  [1,3,2],
  [2,1,3],
  [2,3,1],
  [3,1,2],
  [3,2,1]
]

代码

class Solution {
    public List<List<Integer>> permute(int[] nums) {

         List <List<Integer>> res = new ArrayList<>();
        // speacial case
        if(nums==null || nums.length ==0){
            return res;
        }

        List<Integer> temp = new ArrayList<>();
        temp.add(nums[0]);
        res.add(temp);

        for(int i = 1; i< nums.length; i++){
            int size = res.size();
            while(size>0){
                for(int j = 0; j<=i; j++){
                    List<Integer> list = new ArrayList<>(res.get(0));
                    list.add(j, nums[i]); 
                    res.add(list);
                }
                res.remove(0);
                size--;
            }
        }
      return res;  
    }
}

results matching ""

    No results matching ""