SHARE
TWEET

Untitled

a guest Apr 20th, 2019 70 Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
  1. class Solution {
  2.     public List<List<Integer>> permute(int[] a) {
  3.         List<List<Integer>> result = new ArrayList<>();
  4.         List<Integer> path = new ArrayList<>();
  5.         dfs(-1, a, result, path);
  6.         return result;
  7.     }
  8.     private void dfs(int index, int[] a, List<List<Integer>> result, List<Integer> path){
  9.         if(index != -1){
  10.             path.add(a[index]);
  11.         }
  12.        
  13.         if(index == a.length - 1){
  14.             result.add(new ArrayList<>(path));
  15.         }
  16.        
  17.         for(int i = index + 1; i< a.length; i++){
  18.             swap(index + 1, i, a);
  19.             dfs(index + 1, a, result, path);
  20.             swap(index + 1, i, a);
  21.         }
  22.        
  23.         if(index != -1){
  24.             path.remove(path.size() - 1);
  25.         }
  26.     }
  27.     private void swap(int i, int j, int[] a){
  28.         int temp = a[i];
  29.         a[i] = a[j];
  30.         a[j] = temp;
  31.     }
  32. }
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
 
Top