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]]回溯法,同leetcode78. Subsets
public class Solution { public List<List<Integer>> permute(int[] nums) { List<List<Integer>> permutes = new ArrayList<List<Integer>>(); List<Integer> permute = new ArrayList<Integer>(); helper(permutes, permute, nums); return permutes; } PRivate void helper(List<List<Integer>> permutes, List<Integer> permute, int[] nums) { // 出口 if (permute.size() == nums.length) { permutes.add(new ArrayList<Integer>(permute)); } // 过程 for (int i = 0; i < nums.length; i++) { if(permute.contains(nums[i])) { continue; } permute.add(nums[i]); helper(permutes, permute, nums); permute.remove(permute.size() - 1); } }}新闻热点
疑难解答