https://leetcode.com/problems/permutations/
Given a collection of numbers, return all possible permutations.
For example,
[1,2,3]
have the following permutations:
[1,2,3]
, [1,3,2]
, [2,1,3]
, [2,3,1]
, [3,1,2]
, and [3,2,1]
.
public class Solution {
public List<List<Integer>> permute(int[] num) {
List<List<Integer>> rst = new LinkedList<List<Integer>>();
if(num==null || num.length==0) return rst;
List<Integer> pmt = new LinkedList<Integer>();
HashSet<Integer> index = new HashSet<Integer>();
helper(num, rst, pmt, index);
return rst;
}
public void helper(int[] num, List<List<Integer>> rst, List<Integer> pmt, HashSet<Integer> index){
if(pmt.size()==num.length){
rst.add(new LinkedList<Integer>(pmt));
return;
}
if(pmt.size() > num.length) return;
for(int i=0; i<num.length; i++){
if(index.contains(i)) continue;
pmt.add(num[i]);
index.add(i);
helper(num, rst, pmt, index);
index.remove(i);
pmt.remove(pmt.size()-1);
}
}
}