Simple Permutations using level order.


  • 0
    F

    I like to store array since array operation is faster.
    ...
    public class Solution {
    public List<List<Integer>> permute(int[] nums) {
    List<List<Integer>> list = new ArrayList<List<Integer>>();
    int length = nums.length;
    int index = 0;

        Queue<int[]> q = new LinkedList<int[]>();
        q.add(nums);
        while(!q.isEmpty()){
            int size = q.size();
            
            while(size-- > 0){
                int[] temp = q.remove();
                for(int i = index; i < nums.length; i++){
                    int[] arr = Arrays.copyOf(temp, nums.length);
                    swap(index, i, arr);
                    if(length == 1){
                        List<Integer> sub = convert(temp);
                        list.add(sub);
                    }else{
                        q.add(arr);
                    }
                }
            }
            length--;
            index++;
        }
        return list;
    }
    
    private List<Integer> convert(int[] arr){
        List<Integer> list = new ArrayList<Integer>();
        for(int i : arr){
            list.add(i);
        }
        
        return list;
    }
    
    private void swap(int i, int j, int[] arr){
        int temp = arr[i];
        arr[i] = arr[j];
        arr[j] = temp; 
    }
    

    }
    ...


Log in to reply
 

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.