码迷,mamicode.com
首页 > 其他好文 > 详细

Permutations

时间:2014-10-14 09:58:18      阅读:183      评论:0      收藏:0      [点我收藏+]

标签:style   blog   color   io   os   ar   java   for   sp   

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 {
    public List<List<Integer>> permute(int []num,int index)
    {
        List<List<Integer>> result=new LinkedList<List<Integer>>();
        if(index==num.length)
        {
            List<Integer> p=new ArrayList<Integer>(num.length);
            result.add(p);
            return result;
        }
        for(int i=index;i<num.length;i++)
        {
            int t=num[index];
            num[index]=num[i];
            num[i]=t;
            List<List<Integer>> next=permute(num,index+1);
            for(List<Integer>p:next)
            {
                p.add(0,num[index]);
            }
            result.addAll(next);
            t=num[index];
            num[index]=num[i];
            num[i]=t;
        }
        return result;
    }
    public List<List<Integer>> permute(int[] num) {
        List<List<Integer>> result=new LinkedList<List<Integer>>();
        if(num==null||num.length<=0)
        {
            return result;
        }
        result=permute(num,0);
        return result;
    }
}


Permutations

标签:style   blog   color   io   os   ar   java   for   sp   

原文地址:http://blog.csdn.net/jiewuyou/article/details/40071487

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!