算法46. Permutations

46. Permutations
Given a collection of distinct integers, return all possible permutations.

Example:

Input: [1,2,3]
Output:
[
  [1,2,3],
  [1,3,2],
  [2,1,3],
  [2,3,1],
  [3,1,2],
  [3,2,1]
]
class Solution {
    public List> permute(int[] nums) {
        
    }
}

排列组合,所有数字不重复。

解:
首先想到的是去暴力遍历,外部一层循环,第一个,就是原始数组的顺序,很好理解,但是第二个怎么去排序呢?单靠暴力遍历不太行,所以这题得使用回溯,具体代码如下:

public List> permute(int[] nums) {
    List> list = new ArrayList<>();
    backtrack(list, new ArrayList<>(), nums);
    return list;
}

private void backtrack(List> list, List tempList,
        int[] nums) {
    if (tempList.size() == nums.length) {
        list.add(new ArrayList<>(tempList));
    } else {
        for (int i = 0; i < nums.length; i++) {
            if (tempList.contains(nums[i]))
                continue; // element already exists, skip
            tempList.add(nums[i]);
            backtrack(list, tempList, nums);
            tempList.remove(tempList.size() - 1);
        }
    }
}

你可能感兴趣的:(算法46. Permutations)