Ecosyste.ms: Awesome

An open API service indexing awesome lists of open source software.

Awesome Lists | Featured Topics | Projects

https://github.com/emahtab/permutations

Permutations
https://github.com/emahtab/permutations

leetcode permutations problem-solving recursion

Last synced: about 1 month ago
JSON representation

Permutations

Awesome Lists containing this project

README

        

# Permutations
## https://leetcode.com/problems/permutations

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]
]
```
![Array Permutations](array-permutations.JPG?raw=true "Array Permutations")

# Implementation : Time = O(n * n!)

```java
class Solution {
public List> permute(int[] nums) {
List> result = new ArrayList<>();
permute(result, new ArrayList(), nums);
return result;
}

private void permute(List> result, List permutation, int[] nums) {
if(nums.length == 0){
result.add(permutation);
return;
}
for(int i=0; i < nums.length; i++){
List runningPermutation = new ArrayList(permutation);
runningPermutation.add(nums[i]);
permute(result, runningPermutation, subArray(nums, i));
}
}

private int[] subArray(int[] input, int skipIndex) {
int subArraySize = input.length - 1;
int[] subArray = new int[subArraySize];
int index = 0;
for(int i = 0; i < input.length; i++){
if(i != skipIndex)
subArray[index++] = input[i];
}
return subArray;
}


}
```

### If we are given a String
![String Permutations](string-permutations.JPG?raw=true "String Permutations")
```java
public class Permutation {
public static void main(String[] args) {
permutations("abc");
}

public static void permutations(String str) {
if (str == null || str.length() == 0) {
System.out.println("Input string is empty !!");
return;
} else {
permute("", str);
}
}

public static void permute(String prefix, String remaining) {
if (remaining.length() == 0) {
System.out.println(prefix);
return;
}

for (int i = 0; i < remaining.length(); i++) {
String newPrefix = prefix + remaining.charAt(i);
String newRemaining = remaining.substring(0, i) + remaining.substring(i + 1);
permute(newPrefix, newRemaining);
}
}
}
```