Given a collection of distinct numbers, return all possible permutations.題目要求咱們對於輸入的數字序列,給出它們的全排列。code
例如,
[1,2,3] 有以下的全排列:
[
[1,2,3],
[1,3,2],
[2,1,3],
[2,3,1],
[3,1,2],
[3,2,1]
]rem
public List<List<Integer>> permute(int[] nums) { List<List<Integer>> res = new ArrayList<List<Integer>>(); backtrack(res,new ArrayList<Integer>(),nums); return res; } public void backtrack(List<List<Integer>> res ,List<Integer> tempList,int[] nums){ if(tempList.size() == nums.length){ res.add(new ArrayList<>(tempList)); }else{ for(int i=0;i<nums.length;i++){ if(tempList.contains(nums[i])){ continue; } tempList.add(nums[i]); backtrack(res,tempList,nums); tempList.remove(tempList.size()-1); } } }