zoukankan      html  css  js  c++  java
  • LeetCode:46. Permutations(Medium)

    1. 原题链接

    https://leetcode.com/problems/permutations/description/

    2. 题目要求

    给定一个整型数组nums,数组中的数字互不相同,返回该数组所有的排列组合

    3. 解题思路

    采用递归的方法,使用一个tempList用来暂存可能的排列。

    4. 代码实现

     1 import java.util.ArrayList;
     2 import java.util.List;
     3 
     4 public class Permutations46 {
     5     public static void main(String[] args) {
     6         int[] nums = {2, 1, 3};
     7         for (List l : permute(nums))
     8             System.out.println(l.toString());
     9 
    10     }
    11 
    12     public static List<List<Integer>> permute(int[] nums) {
    13         List<List<Integer>> res = new ArrayList<>();
    14         recursion(res,new ArrayList<>(),nums);
    15         return res;
    16 
    17     }
    18 
    19     private static void recursion(List<List<Integer>> res, List<Integer> tempList,int[] nums){
    20         if(tempList.size()==nums.length)
    21             res.add(new ArrayList<>(tempList));
    22         for(int i =0;i<nums.length;i++){
    23             if(tempList.contains(nums[i])) continue;
    24             tempList.add(nums[i]);
    25             recursion(res,tempList,nums);
    26             tempList.remove(tempList.size()-1);
    27         }
    28     }
    29 }
  • 相关阅读:
    [IOI2013]Dreaming
    Lost Cows
    Mobile Service
    [POI2005]Bank notes
    [CTSC2007]动物园zoo
    [CF1093F]Vasya and Array
    [雅礼集训 2017 Day1]市场
    [APIO2014]序列分割
    [CEOI2004]锯木厂选址
    [APIO2010]特别行动队
  • 原文地址:https://www.cnblogs.com/huiAlex/p/8267903.html
Copyright © 2011-2022 走看看