leetcode 之 Permutations 解题思路

题目如下:

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 class Solution {
    List> list = new ArrayList>();
    public List> permute(int[] num) {
        if(num.length == 0) return list;
        if(num.length == 1){
            List sublist = new ArrayList();
            sublist.add(num[0]);
            list.add(sublist);
            return list;
        }
        int len = num.length;
        int[] out = new int[len];
        int[] used = new int[len];
        doPermute(num, out, used, len, 0);
        return list;
        
        
        
    }
    
    public void doPermute(int[] in, int[] out, int[] used, int length, int current_Len){
        if(current_Len == length){
            List sublist = new ArrayList();
            for(int x : out){
                sublist.add(x);
            }
            list.add(sublist);
            return;
        }
        
        for(int i = 0; i < length; i++){
            if(used[i] == 1){
                continue;
            }
            used[i] = 1;
            out[current_Len] = in[i];
            doPermute(in, out, used,length, current_Len+1);
            used[i] = 0;
        }
    }
}



你可能感兴趣的:(算法)