LeetCode 数组排列组合问题汇总:

       字符的排列组合问题,使用递归+回溯方法。对于有重复元素或者需要组合的元素具有一定顺序,需要先进行排序。

        排列问题因为对所有元素进行排列,判断是否为结果的条件是list的大小和数组的长度相同,否则,依次将没有排列的元素添加到list中,结束一次排列后需要回溯;对于数组元素唯一,只需要在循环中判断list中是否包含该元素,不包含,进行添加,否则,跳过。对于数组元素不唯一,设置Boolean数组来标记是否访问过,并对重复出现的组合去重。

        组合问题相当于对N个元素,挑选M个元素进行全排列,需要将M作为参数进行传递 ,并设置当m==0时结束一次组合,m<0时返回。对于非递减组合,需要事先对数组进行排序,如果结果需要按照size的大小进行排序输出,可以在排列时通过for循环传入m的值,对于数组元素不唯一,可在将元素添加到list中时进行判断,由于已经进行排序,所以,只需要判定当前值与前一个元素不同即可,保证同一层搜索时只选一次一个相同的数。

     常见题解答(均已AC):

 

1.数组元素唯一的全排列:(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].

import java.util.*;
public class Solution {
    ArrayList<ArrayList<Integer>> result  = new ArrayList<ArrayList<Integer>>();
    public ArrayList<ArrayList<Integer>> permute(int[] num) {
        ArrayList<Integer> list = new ArrayList<Integer>();
        dfs(num,list);
        return result;
    }
     public void dfs(int[] num ,ArrayList<Integer> list) {
         if(list.size() == num.length){
            result.add(new ArrayList<Integer>(list));
         }else{
             for(int i = 0 ;i<num.length;i++){
                 if(list.contains(num[i]))
                     continue;
                 list.add(num[i]);
                 dfs(num,list);
                 list.remove(list.size()-1);
             }
         }
     }
}

 

2.数组元素不唯一的全排列:(LeetCode:permutations-ii)

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

import java.util.*;
public class Solution {
    ArrayList<ArrayList<Integer>> result = new ArrayList<ArrayList<Integer>>();
    public ArrayList<ArrayList<Integer>> permuteUnique(int[] num) {
        ArrayList<Integer> list = new ArrayList<Integer>();
        boolean visited[] = new boolean[num.length];
        Arrays.sort(num);
        df
  • 0
    点赞
  • 4
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值