Permutations

来源:互联网 发布:mac 怎么让终端翻墙 编辑:程序博客网 时间:2024/06/05 17:12
Problem:

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

    填空法:先选择一个元素填第一个空,再选择一个元素填第二个空,第二个空的元素不能与第一个空重复,直到所有空被填满,填每一个空时都枚举所有可能。
Solution:
public class Solution {
     boolean[] isUsed;
    List<List<Integer>> res;
    List<Integer> tmp;
    int[] A;
    public List<List<Integer>> permute(int[] num) {
        res = new ArrayList<List<Integer>>();
        if(num==null||num.length==0)
             return res;
         A = num;
        isUsed = new boolean[A.length];
        tmp = new ArrayList<>();
         permuting();
        return res;
    }

    private void permuting(){
        if(tmp.size()==A.length)
            res.add(new ArrayList<>(tmp));
        for(int i=0;i<A.length;i++)
            if(!isUsed[i])
            {
                isUsed[i] = true;
                tmp.add(A[i]);
                permuting();
                tmp.remove(tmp.size()-1);
                isUsed[i] = false;
            }
    }
}
0 0
原创粉丝点击