leetcode 46,47. Permutations I/II 全排列问题 java

46.Permutations
Total Accepted: 96713 Total Submissions: 271529 Difficulty: Medium
Given a collection of distinct 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].

47.Permutations II
Total Accepted: 68800 Total Submissions: 246224 Difficulty: Medium
Given a collection of numbers that might contain duplicates, return all possible unique permutations.

For example,
[1,1,2] have the following unique permutations:
[1,1,2], [1,2,1], and [2,1,1].

排列问题,按照排列思想,遍历每个位置,对每个位置每次都从集合中选一个未被选的元素。所以排列个数为n!,时间复杂度为n!。
对传来的数组利用交换,每次把选择的元素交换到该位置上,再递归后面位置。对于题2有重复元素,要避免交换重复的,所以判断如果出现过就不再交换。

 List<List<Integer>> alllist=new LinkedList<List<Integer>>();
  public List<List<Integer>> permuteUnique(int[] nums) {  
       dfs(nums,0);  
       return alllist;  
    }  
    public void dfs(int[] nums,int s){  
        if(s==nums.length){  
            List<Integer> list=new LinkedList<Integer>();  
            for(int i=0;i<nums.length;i++)  
                list.add(nums[i]);  
            alllist.add(list);  
        }  
        for(int i=s;i<nums.length;i++){  
            boolean flag=false;               //flag题2使用,判断重复的元素,如果是就不交换  
            for(int j=s+1;j<i;j++){           //  
                if(nums[j]==nums[i])          //  
                    flag=true;                //  
            }                                 //  
            if(flag)                          //  
                continue;                     //  
            int tmp=nums[s];  
            nums[s]=nums[i];  
            nums[i]=tmp;  
            dfs(nums,s+1);            
            nums[i]=nums[s];  
            nums[s]=tmp;  

        }  
    }  

这里写图片描述

  • 2
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 2
    评论
评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值