【LeetCode-面试算法经典-Java实现】【046-Permutations(求排列)】

来源:互联网 发布:云计算和超级计算机 编辑:程序博客网 时间:2024/05/01 00:27

【046-Permutations(求排列)】


【LeetCode-面试算法经典-Java实现】【所有题目目录索引】

原题

  Given a collection of 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], and [3,2,1].

题目大意

  给定一个数组,返回他的所有排列。

解题思路

  使用分治法求解。

代码实现

算法实现类

import java.util.*;public class Solution {    private List<List<Integer>> result;    public List<List<Integer>> permute(int[] num) {        result = new LinkedList<>();        if (num != null) {            permute(0, num);        }        return result;    }    private void permute(int i, int[] num) {        if (i == num.length) {            List<Integer> l = new ArrayList<>();            for (int n: num) {                l.add(n);            }            result.add(l);        }else {            for (int j = i; j < num.length; j++) {                swap(num, j, i);                permute(i + 1, num);                swap(num, j, i);            }        }    }    private void swap(int[] A, int x, int y) {        int tmp = A[x];        A[x] = A[y];        A[y] = tmp;    }}

评测结果

  点击图片,鼠标不释放,拖动一段位置,释放后在新的窗口中查看完整图片。

这里写图片描述

特别说明

欢迎转载,转载请注明出处【http://blog.csdn.net/derrantcm/article/details/47098351】

2 0