Java Solution


  • 2
    L

    Given the permutations of the previous n - 1 elements, we can get the permutations for all n elements by inserting the n-th element into different positions in each shorter permutation.

    public List<List<Integer>> permute(int[] nums) {
        List<List<Integer>> result = new ArrayList<>();
        result.add(new ArrayList<Integer>());
        
        for (int i = 0; i < nums.length; i++) {
            List<List<Integer>> current = new ArrayList<>();
            for (List<Integer> list : result) {
                for (int j = 0; j < list.size() + 1; j++) {
                    ArrayList<Integer> cur = new ArrayList<>(list);
                    cur.add(j, nums[i]);
                    current.add(cur);
                }
            }
            result = current;
        }
        return result;  
    

    '''


Log in to reply
 

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