LeetCode全排列 java实现

import java.util.ArrayList;
import java.util.List;

/**
 * @author chengxy
 * @date 2018/6/27 10:57
 * 全排列 https://leetcode-cn.com/problems/permutations/description/1
 */
public class DemoTest0627 {
    public static void main(String[] args) {
        int nums[] ={1,2,3};
        List> permute = permute(nums);
        for (int i = 0;iout.println(permute.get(i));
        }

    }

    public static List> permute(int[] nums) {
        if (nums.length < 1) {
            return null;
        }
        //总集合
        List> allList = new ArrayList();
        allList = permutation(nums, allList,  0);
        return allList;

    }

    public static   List permutation(int[] nums, List> allList,  int start) {
        List list = new ArrayList<>();
        if (start == nums.length - 1) {
            for (int i = 0; i < nums.length; i++) {
                list.add(nums[i]);
            }
            allList.add(list);
        } else {
            for (int i = start; i < nums.length; i++) {
                change(nums, i, start);
                permutation(nums, allList, start + 1);
                change(nums, start, i);

            }

        }

        return allList;
    }

    public static int[] change(int[] nums, int i, int start) {
        int emp;
        emp = nums[i];
        nums[i] = nums[start];
        nums[start] = emp;
        return nums;
    }

}

你可能感兴趣的:(LeetCode)