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

Example:

Input: [1,2,3]
Output:
[
  [1,2,3],
  [1,3,2],
  [2,1,3],
  [2,3,1],
  [3,1,2],
  [3,2,1]
]

Solution 1:
class Solution {
    List<List<Integer>> returnList = new ArrayList<>();
    int[] used ;
    public List<List<Integer>> permute(int[] nums) {
        List<Integer> temp = new ArrayList<Integer>();
        used = new int[nums.length];
         findPermutations(nums, 0, temp);
        return returnList;
    }
    
    public void findPermutations(int[] nums, int index, List<Integer> temp){
        
        if(index == nums.length){
            returnList.add(new ArrayList(temp));
            return;
        }
        
        for(int i=0;i<nums.length;i++){
            if(used[i]!=1){
                used[i]=1;
                temp.add(nums[i]);
                findPermutations(nums, index+1, temp);
                temp.remove(temp.size()-1);
                used[i] = 0;
            }
        }
        return;
    }
}
rajendra

Recent Posts

Largest Unique Number Java Solution

Question : Given an array of integers A, return the largest integer that only occurs once.…

9 months ago

Jump Search Algorithm In Java

Jump search algorithm is a pretty new algorithm to search for an element in a…

1 year ago

Knuth Morris Pratt Pattern Search Algorithm

What is Knuth Morris Pratt or KMP algorithm ? KMP is an algorithm which is…

1 year ago

Binary Search Algorithm In Java

Binary Search is a Logarithmic search which finds the target element in a sorted array…

1 year ago

Leetcode Integer to Roman Java Solution

Roman numerals are represented by seven different symbols: I, V, X, L, C, D and M. Symbol Value I 1 V 5 X…

2 years ago

Leetcode Container With Most Water Java Solution

Given n non-negative integers a1, a2, ..., an , where each represents a point at coordinate (i, ai). n vertical lines are drawn such…

2 years ago

This website uses cookies.