Given a collection of distinct 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], [3,2,1] ]
思路: backtrack
public class Solution { public List<List<Integer>> permute(int[] nums) { List<List<Integer>> result = new ArrayList<List<Integer>>(); if(nums == null || nums.length == 0) { return result; } ArrayList<Integer> list = new ArrayList<Integer>(); helper(result,list,nums); return result; } public void helper(List<List<Integer>> result, ArrayList<Integer> list, int[] nums) { if(list.size() == nums.length) { result.add(new ArrayList<Integer>(list)); } for(int i = 0; i < nums.length; i++) { if(list.contains(nums[i])) { continue; } list.add(nums[i]); helper(result,list,nums); list.remove(list.size() - 1); } } }