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

LeetCode - Permutations

时间:2015-12-25 13:33:01      阅读:83      评论: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,就是

[1,2],[2,1],然后往这两个集合中插入3,就是

[3,1,2] [1,3,2] [1,2,3]

[3,2,1] [2,3,1] [2,1,3]

package permutation;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

public class Permutations {

    public List<List<Integer>> permute(int[] nums) {
        List<List<Integer>> res = new ArrayList<List<Integer>>();
        Arrays.sort(nums);
        List<Integer> subRes = new ArrayList<Integer>();
        subRes.add(nums[0]);
        res.add(subRes);
        return permute(res, nums, 1);
    }
    
    private List<List<Integer>> permute(List<List<Integer>> res, int[] nums, int pos) {
        if (pos >= nums.length) return res;
        List<List<Integer>> newRes = new ArrayList<List<Integer>>();
        for (List<Integer> subRes : res) {
            int count = subRes.size();
            for (int i = 0; i <= count; ++i) {
                List<Integer> newSubRes = new ArrayList<Integer>(subRes);
                newSubRes.add(i, nums[pos]);
                newRes.add(newSubRes);
            }
        }
        return permute(newRes, nums, pos + 1);
    }
    
    public static void main(String[] args) {
        // TODO Auto-generated method stub
        Permutations p = new Permutations();
        int[] nums = { 1,1,1 };
        List<List<Integer>> res = p.permute(nums);
        for (List<Integer> l : res) {
            for (int i : l)
                System.out.print(i + "\t");
            System.out.println();
        }
    }

}

 

LeetCode - Permutations

标签:

原文地址:http://www.cnblogs.com/shuaiwhu/p/5075551.html

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