全排列

思想

回溯法

  1. 确定一位,其余位求全排列
  2. 当low == high时,确定了一种情况,加入集合

代码实现

class Solution {
    List<List<Integer>> ans= new ArrayList<>();

    public List<List<Integer>> permute(int[] nums) {
        MyPermute(nums,0,nums.length - 1);
        return ans;
    }

    public void MyPermute(int[] nums, int low, int high){
        if (low == high){
            List<Integer> list = new ArrayList<Integer>();
            for (int i = 0; i < nums.length; i++) {
                list.add(nums[i]);
            }
            ans.add(list);
        }else {
            for (int i = low; i <= high; i++) {
                swap(nums,low,i);
                MyPermute(nums,low + 1, high);
                swap(nums,low,i);
            }
        }
    }

    public void swap(int[] nums,int i, int j){
        int temp = nums[i];
        nums[i] = nums[j];
        nums[j] = temp;
    }
}