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]
]
package leetCode; import java.util.ArrayList; import java.util.List; /** * Created by lxw, liwei4939@126.com on 2018/3/8. */ /* 为了生成所有的排列组合,当我们在递归调用栈时,需要删除最 近添加的元素,在for循环的第一次迭代过程中,添加了以nums[0] 开头所有的排列;此后当建立以nums[1]开头的排列时需要清除tmplist, 它包含了for循环的第一次迭代的排列 */ public class L046_Permutation { public List<List<Integer>> permute(int[] nums){ List<List<Integer>> list = new ArrayList<>(); backTrack(list, new ArrayList<>(), nums); return list; } private void backTrack(List<List<Integer>> list, List<Integer> tmpList,int[] nums){ if (tmpList.size() == nums.length){ list.add(new ArrayList<>(tmpList)); } else { for (int i= 0; i < nums.length; i++){ if (tmpList.contains(nums[i])){ continue; } tmpList.add(nums[i]); backTrack(list, tmpList, nums); tmpList.remove(tmpList.size() - 1); } } } public static void main(String[] args){ L046_Permutation tmp = new L046_Permutation(); int[] arr = new int[]{1, 2, 3}; List<List<Integer>> res = tmp.permute(arr); System.out.println(res); } }关于回溯法,参考https://leetcode.com/problems/permutations/discuss/18239/A-general-approach-to-backtracking-questions-in-Java-(Subsets-Permutations-Combination-Sum-Palindrome-Partioning)