zoukankan      html  css  js  c++  java
  • 46. Permutations 全排列,无重复

    Given a collection of distinct integers, return all possible permutations.

    Example:

    Input: [1,2,3]
    Output:
    [
      [1,2,3],
      [1,3,2],
      [2,1,3],
      [2,3,1],
      [3,1,2],
      [3,2,1]
    ]

    在其基础上扩展,所以是i + 1。要有个start index的参数

    //跳过重复值,同一temp集合中不能出现两次
    if(temp.contains(nums[i])) continue;

    class Solution {
        public List<List<Integer>> permute(int[] nums) {
            //cc
            List<List<Integer>> results = new ArrayList<List<Integer>>();
            if (nums == null || nums.length == 0) 
                return results;
            
            Arrays.sort(nums);
            dfs(nums, new ArrayList<Integer>(), 0, results);
            
            return results;
        }
        
        public void dfs(int[] nums, List<Integer> temp, int start,
                        List<List<Integer>> results) {
            //exit 退出的条件,加在dfs里最外一层
           if (temp.size() == nums.length) {
               results.add(new ArrayList<>(temp));
           }
                   
            for (int i = 0; i < nums.length; i++) {
                if (temp.contains(nums[i]))
                    continue;
                
                temp.add(nums[i]);
                dfs(nums, temp, i + 1, results);
                temp.remove(temp.size() - 1);
            }
        }
    }
    View Code
     
     
  • 相关阅读:
    MongoDB的简单操作
    MongoDB下载安装
    enctype="multipart/form-data" form表单提交值为null
    shiro
    json简单介绍
    Sql Server 安装
    MySQL面试常问的查询操作
    关于分页
    Vuex
    Vue基础安装(精华)
  • 原文地址:https://www.cnblogs.com/immiao0319/p/13868102.html
Copyright © 2011-2022 走看看