zoukankan      html  css  js  c++  java
  • 数组全排列

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

    /**
    * 给定一个不含重复数字的数组 nums ,返回其 所有可能的全排列 。你可以 按任意顺序 返回答案。
    *
    * 示例 1:
    *
    * 输入:nums = [1,2,3]
    * 输出:[[1,2,3],[1,3,2],[2,1,3],[2,3,1],[3,1,2],[3,2,1]]
    */
    public class PrintAllPermutations {

    public static void main(String[] args) {
    PrintAllPermutations printAllPermutations = new PrintAllPermutations();
    int[] nums = new int[]{1, 2, 3, 4};
    List<List<Integer>> list = printAllPermutations.getAllList(nums);

    for (List<Integer> integers : list) {
    System.out.println(integers.toString());
    }
    }

    public List<List<Integer>> getAllList(int[] arr) {
    List<List<Integer>> list = new ArrayList<>();
    List<Integer> sublist = new ArrayList<>();
    getAllList(arr, 0, list, sublist);
    return list;
    }

    private void getAllList(int[] arr, int j, List<List<Integer>> list, List<Integer> sublist) {
    if (j == arr.length) {
    list.add(new ArrayList<>(sublist));
    return;
    }

    sublist.add(arr[j]);
    getAllList(arr, j + 1, list, sublist);
    sublist.remove(sublist.size() - 1);
    for (int k = j + 1; k < arr.length; k++) {
    swap(arr, j, k);
    sublist.add(arr[j]);
    getAllList(arr, j + 1, list, sublist);
    sublist.remove(sublist.size() - 1);
    swap(arr, j, k);
    }
    }

    private void swap(int[] arr, int j, int k) {
    int temp = arr[j];
    arr[j] = arr[k];
    arr[k] = temp;
    }

    }

    /* 如有意见或建议,欢迎评论区留言;如发现代码有误,欢迎批评指正 */
  • 相关阅读:
    字符串与字典常用命令
    Python学习之路:字符串常用操作
    Python学习之路:购物车实例
    面试题2017
    c#语法学习
    结构化设计模式-桥接模式
    结构型设计模式-适配器模式
    .Net Cache
    设计模式的六大原则
    uml类图关系
  • 原文地址:https://www.cnblogs.com/laydown/p/15685278.html
Copyright © 2011-2022 走看看