首页 > 学院 > 开发设计 > 正文

leetcode46. Permutations

2019-11-06 07:06:54
字体:
来源:转载
供稿:网友

46. Permutations

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); } }}

这里写图片描述


发表评论 共有条评论
用户名: 密码:
验证码: 匿名发表