sweet1cris

Untitled

Sep 5th, 2017
126
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Java 0.82 KB | None | 0 0
  1. public class Solution {
  2.   // approach: DFS
  3.   // time complexity: O(n!)
  4.   // space complexity: O(n)
  5.   public List<String> permutations(String set) {
  6.     List<String> result = new ArrayList<>();
  7.     if (set == null) {
  8.       return result;
  9.     }
  10.     char[] array = set.toCharArray();
  11.     helper(array, result, 0);
  12.     return result;
  13.   }
  14.   private void helper(char[] array, List<String> result, int index) {
  15.     // base case
  16.     if (index >= array.length - 1) {
  17.       result.add(new String(array));
  18.       return;
  19.     }
  20.    
  21.     for (int i = index; i < array.length; i++) {
  22.       swap(array, i, index);
  23.       helper(array, result, index + 1);
  24.       swap(array, i, index);
  25.     }
  26.   }
  27.   private void swap(char[] array, int i, int j) {
  28.     char temp = array[i];
  29.     array[i] = array[j];
  30.     array[j] = temp;
  31.   }
  32. }
Advertisement
Add Comment
Please, Sign In to add comment