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

      

      

  • 相关阅读:
    机器学习任务攻略
    2.0 线性模型_李宏毅2021
    PyTorch
    jupyter切换虚拟环境
    python中yield的用法详解——最简单,最清晰的解释
    Full卷积、Same卷积、Valid卷积、带深度的一维卷积
    计算机环境变量的配置,以java为例以及eclipse简要设置
    conda创建/移除虚拟环境
    bak
    JSoup抓取本地页面
  • 原文地址:https://www.cnblogs.com/averillzheng/p/3542226.html
Copyright © 2020-2023  润新知