Java solution with time complexity of 2N!


  • 0
    G
    public class Solution {
    private List<List<Integer>> result;
    private int[] p;
    
    public List<List<Integer>> permute(int[] nums) {
        result = new ArrayList<List<Integer>>();
        p = nums;
        
        generate(nums.length - 1);
        return result;
    }
    
    private void add_result() {
        List<Integer> ans = new ArrayList<Integer>();
        for (int i: p) {
            ans.add(i);
        }
        result.add(ans);
    }
    
    private void generate(int N) {
        int c;
        if (N == 0) {
            add_result();
        }
        for (c = 0; c <= N; c++) {
            exch(c, N);
            generate(N - 1);
            exch(c, N);
        }
    }
    
    private void exch (int i, int j) {
        int t = p[i];
        p[i] = p[j];
        p[j] = t;
    }
    }

Log in to reply
 

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