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;
        }
    }
    

      

      

  • 相关阅读:
    《大道至简》第一章 编程的精义
    java课堂练习7
    Java课后练习6
    Java课后练习5
    Java课后练习4
    Java课后练习3
    课堂练习
    求和程序实验报告
    大道至简第二章读后感
    课堂作业例子
  • 原文地址:https://www.cnblogs.com/averillzheng/p/3542226.html
Copyright © 2011-2022 走看看