Facebook
From Sefira, 6 Months ago, written in Plain Text.
Embed
Download Paste or View Raw
Hits: 302
  1. import java.util.ArrayList;
  2. import java.util.List;
  3.  
  4. public class Permutations {
  5.  
  6.     public List<List<Integer>> permutation(int nums[]) {
  7.         List<List<Integer>> answer = new ArrayList<>();
  8.         backtrack(answer, new ArrayList<>(), nums);
  9.         return answer;
  10.     }
  11.  
  12.     public void backtrack(List<List<Integer>> answer,  List<Integer> tempList, int [] nums) {
  13.  
  14.         if(tempList.size() == nums.length){
  15.             answer.add(new ArrayList<>(tempList));
  16.         } else{
  17.             for(int i = 0; i < nums.length; i++){
  18.                 if(tempList.contains(nums[i])) {
  19.                     continue; // element already exists, skip
  20.                 }
  21.                 tempList.add(nums[i]);
  22.                 backtrack(answer, tempList, nums);
  23.                 tempList.remove(tempList.size() - 1);
  24.             }
  25.         }
  26.     }
  27.  
  28.     public static void main(String args[]) {
  29.         Permutations p = new Permutations();
  30.         int nums[] = {1,2,3};
  31.         System.out.println(p.permutation(nums));
  32.     }
  33. }
  34.