首页 > 其他 > 详细

leetcode--Permutations

时间:2014-02-10 13:07:51      阅读:270      评论:0      收藏:0      [点我收藏+]

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

 

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
public class Solution {
    public ArrayList<ArrayList<Integer>> permute(int[] num) {
       ArrayList<ArrayList<Integer> > result = new ArrayList<ArrayList<Integer> >();
        if(num.length > 0){
            ArrayList<Integer> list = new ArrayList<Integer>();
            list.add(num[0]);
            result.add(list);
            int length = 1;
            for(int i = 1; i < num.length; ++i){
                length *= i;
                for(int j = 0; j < length; ++j){
                    ArrayList<Integer> newList = result.remove(0);
                    for(int k = 0; k < i + 1; ++k){
                        ArrayList<Integer> addedList = new ArrayList<Integer>();
                        addedList.addAll(newList);
                        addedList.add(k, num[i]);
                        result.add(addedList);
                    }  
                }
            }  
        }      
        return result;
    }
}

  

leetcode--Permutations

原文:http://www.cnblogs.com/averillzheng/p/3542226.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!