leecode 排列的学习

本文探讨了如何处理含有重复数字的排列问题,并通过实例展示了利用递归和过滤条件来生成唯一排列的方法。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

前面写过3个排列。这里再写一次。

1.全部都不重复https://oj.leetcode.com/problems/permutations/

(使用交换法)只是本人对c++ stl不熟,不会把排列结果保存,这里用java写一遍。

 1 public class Solution {
 2     public List<List<Integer>> permute(int[] num) {
 3         
 4        
 5        ArrayList<ArrayList<Integer>> total=new    ArrayList<ArrayList<Integer>>();
 6      
 7         if(num.length==0) return (List)total;
 8        int lev=0;
 9        per(total,num,lev);
10         return  (List)total;
11         
12     }
13     public void swap(int num[],int i,int j)
14     {
15         int temp=num[i];
16         num[i]=num[j];
17         num[j]=temp;
18         
19     }
20     
21     public void per(ArrayList<ArrayList<Integer>> total,int num[],int lev)
22     {
23         if(lev==num.length)
24         {
25             ArrayList ar=new ArrayList<Integer>();
26             for(int i=0;i<num.length;i++)
27             {
28                 ar.add(num[i]);
29             }
30             total.add(ar);
31 
32         }
33         else
34         {
35             for(int i=lev;i<num.length;i++)
36             {
37                 swap(num,lev,i);
38                
39                 per(total,num,lev+1);
40                 swap(num,lev,i);
41                 
42                 
43             }
44             
45             
46         }
47         
48         
49     }
50 }

2.

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].

思路就是 假设当前考虑的是第一位的2 ,只有第一个1需要交换,因为 1 21 和1 12 对于,21和12排列都向等,所以,在前文的基础上加上一个过滤的交换条件就行

 

 

 

转载于:https://www.cnblogs.com/hansongjiang/p/3823009.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值