Ecosyste.ms: Awesome
An open API service indexing awesome lists of open source software.
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
- Host: GitHub
- URL: https://github.com/emahtab/permutations
- Owner: eMahtab
- Created: 2019-11-04T01:24:28.000Z (about 5 years ago)
- Default Branch: master
- Last Pushed: 2024-10-27T09:52:04.000Z (2 months ago)
- Last Synced: 2024-10-27T11:05:49.366Z (2 months ago)
- Topics: leetcode, permutations, problem-solving, recursion
- Language: Java
- Homepage:
- Size: 56.6 KB
- Stars: 1
- Watchers: 1
- Forks: 0
- Open Issues: 0
-
Metadata Files:
- Readme: README.md
Awesome Lists containing this project
README
# Permutations
## https://leetcode.com/problems/permutationsGiven 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);
}
}
}
```