leetcode46. Permutations

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> permute(int[] nums) {
        List> permutes = new ArrayList>();
        List permute = new ArrayList();
        helper(permutes, permute, nums);
        return permutes;

    }
    private void helper(List> permutes, List permute, int[] nums) {
        // 出口
        if (permute.size() == nums.length) {
            permutes.add(new ArrayList(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);
        }
    }
}

leetcode46. Permutations_第1张图片

你可能感兴趣的:(leetcode)