求排列

原題

  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].java

題目大意

  給定一個數組,返回他的全部排列。算法

解題思路

  使用分治法求解。數組

代碼實現

算法實現類spa

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;
    }
}
相關文章
相關標籤/搜索