欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页

LeetCode 46 - Permutations

程序员文章站 2024-01-18 09:40:22
...

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

 

public List<List<Integer>> permute(int[] num) {
    List<List<Integer>> result = new ArrayList<>();
    perm(result, num, 0);
    return result;
}

public void perm(List<List<Integer>> result, int[] num, int pos) {
    if(pos == num.length) {
        List<Integer> list = new ArrayList<Integer>();
        for(int a:num) list.add(a);
        result.add(list);
        return;
    }
    for(int i=pos; i<num.length; i++) {
        swap(num, i, pos);
        perm(result, num, pos+1);
        swap(num, i, pos);
    }
}

private void swap(int[] num, int i, int j) {
    int tmp = num[i];
    num[i] = num[j];
    num[j] = tmp;
}