SHARE
TWEET

Untitled

a guest Sep 16th, 2019 98 Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
  1. /*
  2. https://leetcode.com/problems/permutations/
  3. Runtime: 37 ms, faster than 5.01% of Java online submissions for Permutations.
  4. Memory Usage: 37.4 MB, less than 95.74% of Java online submissions for Permutations.
  5. */
  6. class Solution {
  7.     public List<List<Integer>> permute(int[] nums) {
  8.         ArrayList<List<Integer>> output = new ArrayList<>();
  9.         List<Integer> numbers = Arrays.stream(nums).boxed().collect(Collectors.toList());
  10.         for (int step = 0, il = factorial(nums.length); step < il; step++) {
  11.             output.add(new ArrayList<>(numbers));
  12.             int i = nums.length - 2;
  13.             while (i > -1 && numbers.get(i) >= numbers.get(i + 1)) {
  14.                 --i;
  15.             }
  16.             if (i > -1) {
  17.                 int j = i + 1;
  18.                 while (j < nums.length && numbers.get(i) < numbers.get(j)) {
  19.                     ++j;
  20.                 }
  21.                 Collections.swap(numbers, i, j - 1);
  22.             }
  23.             for (int s = i + 1, e = nums.length - 1; s < e; ++s, --e) {
  24.                 Collections.swap(numbers, s, e);
  25.             }
  26.         }
  27.         return output;
  28.     }
  29.  
  30.     static int factorial(int n) {
  31.         int result = 1;
  32.         for (int i = 1; i <= n; i++) {
  33.             result *= i;
  34.         }
  35.         return result;
  36.     }
  37. }
RAW Paste Data
We use cookies for various purposes including analytics. By continuing to use Pastebin, you agree to our use of cookies as described in the Cookies Policy. OK, I Understand
Not a member of Pastebin yet?
Sign Up, it unlocks many cool features!
 
Top