Algorithm:
take one number, permute it with permutation of rest of numbers, so recursive is a natural call.
length here is same length as number of numbers.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 | class Solution { /** * @param nums: A list of integers. * @return: A list of permutations. */ public ArrayList<ArrayList<Integer>> permute(ArrayList<Integer> nums) { // write your code here ArrayList<ArrayList<Integer>> result = new ArrayList<ArrayList<Integer>>(); if(nums==null)return result; ArrayList<Integer> pList = new ArrayList<Integer>(); permuteRest(nums,pList,result); return result; } //pList: element path. I am basically building up the pList with recursive calls void permuteRest(ArrayList<Integer> nums,ArrayList<Integer> pList, ArrayList<ArrayList<Integer>> result){ if(pList.size()==nums.size()){ ArrayList<Integer> al = new ArrayList<Integer>(); al.addAll(pList); result.add(al); return; } //main body:all number, permute with permutation of rest numbers for(Integer i:nums){ if(!pList.contains(i)){ pList.add(i); permuteRest(nums,pList,result); pList.remove(i); } } } } |
No comments:
Post a Comment