zoukankan      html  css  js  c++  java
  • 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 {
        /**
    	 * dynamic programming method.
    	 * the permutation contains num[0] is one.
    	 * For num[1], there are two place to insert it and get two lists <num[1], num[0]>, <num[0], num[1]>. Using
    	 * this idea, if we have insert num[i - 1] and get their permutaton, now we insert num[i] into each list.
    	 * There are (i + 1) position (=length of list + 1) to place num[i].
    	 * @param num --Integer array.
    	 * @return List<List<Integer>> --the collection of all permutation of num.
    	 * @author Averill Zheng
    	 * @version 2014-06-05
    	 * @since JDK 1.7
    	 */
    	public List<List<Integer>> permute(int[] num) {
    		List<List<Integer> > result = new ArrayList<List<Integer>>();
    		int length = num.length;
    		if(length > 0){
    			List<Integer> startList = new ArrayList<Integer>();
    			startList.add(num[0]);
    			result.add(startList);
    			int size = 1;
    			for(int i = 1; i < length; ++i){
    				List<List<Integer>> tempResult = new ArrayList<List<Integer> >();
    				for(int j = 0; j < size; ++j){
    					List<Integer> aList = result.get(j);
    					for(int k = 0; k < i + 1; ++k){
    						List<Integer> newList = new ArrayList<Integer>();
    						newList.addAll(aList);
    						newList.add(k, num[i]);
    						tempResult.add(newList);
    					}	
    				}
    				size *= (i + 1);
    				result = tempResult;
    			}
    		}
    		return result;
        }
    }
    

      

      

  • 相关阅读:
    P2420 让我们异或吧(倍增)
    bzoj题目分类
    hash练习们
    bzoj1433[ZJOI2009]假期的宿舍(匈牙利)
    bzoj2427:[HAOI2010]软件安装(Tarjan+tree_dp)
    bzoj2730矿场搭建(Tarjan割点)
    codevs4511信息传递(Tarjan求环)
    进入js
    css层叠样式表
    HTML超文本标记语言
  • 原文地址:https://www.cnblogs.com/averillzheng/p/3542226.html
Copyright © 2011-2022 走看看