算法基础——递归 / 回溯(二)

一、全排列 II

  • 递归过程就像二叉树,每一层递归结束后(回溯),看情况清理枝叶
  • 递归函数结束条件:当传入的排列结果长度等于数组长度
  • 递归函数执行:
    • 循环数组查找,当该元素未被访问
    • 将其标记被访问,是排列的一部分
    • 然后加入排列结果中(至于new的原因:传入的排列可能会有很多新的相关排列,也即是非叶结点)
    • 接着调用递归函数,再次组成排列结果
    • 函数返回后(回溯):判断目前这个元素在数组中是否重复
      • 重复是不需要再用来构造排序的
      • 因为数组是被排序过了,所以循环遍历,直到越界或者不等于
    • 该元素要被重新标记为未加入排列,因为可以在下一个元素的下一层递归中,构建出新的排列
class Solution {
    public List<List<Integer>> permuteUnique(int[] nums) {
        Arrays.sort(nums);//数组排序
        List<List<Integer>> ans = new ArrayList<>();
        checkBack(nums, new int[nums.length], ans, new ArrayList<Integer>());
        return ans;
    }

    private void checkBack(int[] nums, int[] memory, List<List<Integer>> ans, List<Integer> permute) {
        if(permute.size() == nums.length) {
            ans.add(permute);
        } else {
            for(int i = 0; i < nums.length; i++) {//遍历数组
                if(memory[i] == 0) {//到当前递归,数组中的值不在当前传入permute中
                    memory[i] = 1;//现在在了
                    List<Integer> tpermute = new ArrayList<>(permute);
                    tpermute.add(nums[i]);
                    checkBack(nums, memory, ans, tpermute);//进行下一层递归
                    memory[i] = 0;//递归结束就还未出现在往后构造的排列中
                    while(i < nums.length - 1 && nums[i] == nums[i + 1]) {//处理重复的排列元素,不需要重复的排列
                        i++;//即使最后一个还是重复的,当时在外循环中,i自增后判断结果越界,结束循环。递归结束
                    }
                }
            }
        }
    }
}

二、组合总和

  • 题目条件

    • 无重复元素
    • candidates数组中的元素可无限制重复选取
    • 数字值、数量不相等的组合就是唯一的
    • 给定数组不一定按升序排列
  • 思路:

    • 类似二叉树
    • 递归回溯处理
    • 每次循环从下标index开始,保证前面的元素不再选取,因为哪些组合早已出现过
      • index就是限制组合的重复构成
    • 题目要求组合的元素在数组无限选取
      • 循环数组开始就要有个index开始,防止重复
    • 递归调用函数时,将组合sum值传入,提高效率
      • 当sum和target相同,即可得到一个组合结果
      • 递归的结束
    • 循环的另一个条件sum + 当前 下标元素不大于target
      • 否则结束循环,递归结束
      • 数组需先排序,从而减少没必要的递归(值比target大)
  • class Solution {
        public List<List<Integer>> combinationSum(int[] candidates, int target) {
            Arrays.sort(candidates);//先排序
            List<List<Integer>> ans = new ArrayList<>();
            checkBack(ans, candidates, target, 0, new ArrayList<Integer>(), 0);//递归开始,从下标0元素开始
            return ans;
        }
    
        private void checkBack(List<List<Integer>> ans, int[] candidates, int target, int index, List<Integer> combination, int sum) {
            if(target == sum) {//当值已是target
                ans.add(combination);
            } else if(target > sum) {
                for(int i = index; i < candidates.length && sum + candidates[i] <= target; i++) {//当前下标不越界且加上sum不大于target
                    List<Integer> tcom = new ArrayList<>(combination);//new一个新的组合结果
                    tcom.add(candidates[i]);//添加当前的下标元素
                    checkBack(ans, candidates, target, i, tcom, sum + candidates[i]);//下次递归时,数组循环从当前下标开始,前面的元素无需重复选取,否则将出现重复的组合
                }
            }
        }
    }
    

三、组合总和 II

  • 题目条件

    • 数组 candidates存在重复的元素
    • 数组 candidates中的元素在每个组合中只能使用一次
    • 组合不能重复
    • 数组 candidates并非一定升序
  • 思路:

    • 先将数组 candidates升序排列
    • 递归回溯处理
      • 循环数组的每个元素,同时当下标值 + 传入sum 不大于target
        • sum:上层递归的值总和,也是传入combination的值总和
      • 当前下标在memory中值为0:未被访问,可作为组合一部分
      • 然后将该下标在memory记录为已使用、同时添加到队列
        • 队列的作用:记录这一层递归中循环使用了的元素,循环结束才可将这些元素在memory中标记为未被使用的初始状态
        • 为什么:在下一层循环中,不能重复使用已在组合内的元素;同一层循环内:不能使用前面构成的组合的元素
        • 保证不重复组合的关键
      • 调用函数递归
      • 由于存在重复元素,不需要再次使用构成数组
        • 改变下标、记录memory、queue内即可
      • 循环访问数组元素结束:循环queue,改变memory值
    • 当target = sum,得到一个组合结果,添加到结果集合
  • class Solution {
        public List<List<Integer>> combinationSum2(int[] candidates, int target) {
            Arrays.sort(candidates);//排序数组
            List<List<Integer>> ans = new ArrayList<>();
            checkBack(ans, candidates, target, new int[candidates.length], new ArrayList<Integer>(), 0);
            return ans;
        }
    
        private void checkBack(List<List<Integer>> ans, int[] candidates, int target, int[] memory, List<Integer> combination, int sum) {
            if(target == sum) {//是一个组合结果,加入到结果集合
                ans.add(combination);
            } else if(target > sum) {
                Queue<Integer> queue = new LinkedList<>();//记录循环中被标记已访问的下标
                for(int i = 0; i < candidates.length && sum + candidates[i] <= target; i++) {
                    if(memory[i] == 0) {//未被访问
                        memory[i] = 1;//标记是组合一部分
                        queue.offer(i);//入队
                        List<Integer> tcom = new ArrayList<>(combination);
                        tcom.add(candidates[i]);//构造新组合
                        checkBack(ans, candidates, target, memory, tcom, sum + candidates[i]);
                        while(i < candidates.length - 1 && candidates[i] == candidates[i + 1]) {//将下标指向不重复的元素,同时也要标记这些重复元素被使用(假使用,也即是不能用)
                            i++;
                            memory[i] = 1;
                            queue.offer(i);
                        }
                    }
                }
                while(!queue.isEmpty()) {//恢复元素的可用性
                    memory[queue.poll()] = 0;
                }
            }
        }
    }
    
  • 改进:

    • 因为数组已排序

    • 使用下标变化可达到标记效果

    • 调用函数传入当前下标 加 1 值,作为下一层递归中,循环开始的下标

      • 将不会存在重复访问元素的情况
      • 构造组合的元素不会在数组中重复选取
    • class Solution {
          public List<List<Integer>> combinationSum2(int[] candidates, int target) {
              Arrays.sort(candidates);
              List<List<Integer>> ans = new ArrayList<>();
              checkBack(ans, candidates, target, 0, new ArrayList<Integer>(), 0);
              return ans;
          }
      
          private void checkBack(List<List<Integer>> ans, int[] candidates, int target, int index, List<Integer> combination, int sum) {
              if(target == sum) {
                  ans.add(combination);
              } else if(target > sum) {
                  for(int i = index; i < candidates.length && sum + candidates[i] <= target; i++) {
                      List<Integer> tcom = new ArrayList<>(combination);
                      tcom.add(candidates[i]);
                      checkBack(ans, candidates, target, i + 1, tcom, sum + candidates[i]);
                      while(i < candidates.length - 1 && candidates[i] == candidates[i + 1]) {//将下标指向不重复的元素
                          i++;
                      }
                  }
              }
          }
      }
      
©著作权归作者所有,转载或内容合作请联系作者
  • 序言:七十年代末,一起剥皮案震惊了整个滨河市,随后出现的几起案子,更是在滨河造成了极大的恐慌,老刑警刘岩,带你破解...
    沈念sama阅读 216,919评论 6 502
  • 序言:滨河连续发生了三起死亡事件,死亡现场离奇诡异,居然都是意外死亡,警方通过查阅死者的电脑和手机,发现死者居然都...
    沈念sama阅读 92,567评论 3 392
  • 文/潘晓璐 我一进店门,熙熙楼的掌柜王于贵愁眉苦脸地迎上来,“玉大人,你说我怎么就摊上这事。” “怎么了?”我有些...
    开封第一讲书人阅读 163,316评论 0 353
  • 文/不坏的土叔 我叫张陵,是天一观的道长。 经常有香客问我,道长,这世上最难降的妖魔是什么? 我笑而不...
    开封第一讲书人阅读 58,294评论 1 292
  • 正文 为了忘掉前任,我火速办了婚礼,结果婚礼上,老公的妹妹穿的比我还像新娘。我一直安慰自己,他们只是感情好,可当我...
    茶点故事阅读 67,318评论 6 390
  • 文/花漫 我一把揭开白布。 她就那样静静地躺着,像睡着了一般。 火红的嫁衣衬着肌肤如雪。 梳的纹丝不乱的头发上,一...
    开封第一讲书人阅读 51,245评论 1 299
  • 那天,我揣着相机与录音,去河边找鬼。 笑死,一个胖子当着我的面吹牛,可吹牛的内容都是我干的。 我是一名探鬼主播,决...
    沈念sama阅读 40,120评论 3 418
  • 文/苍兰香墨 我猛地睁开眼,长吁一口气:“原来是场噩梦啊……” “哼!你这毒妇竟也来了?” 一声冷哼从身侧响起,我...
    开封第一讲书人阅读 38,964评论 0 275
  • 序言:老挝万荣一对情侣失踪,失踪者是张志新(化名)和其女友刘颖,没想到半个月后,有当地人在树林里发现了一具尸体,经...
    沈念sama阅读 45,376评论 1 313
  • 正文 独居荒郊野岭守林人离奇死亡,尸身上长有42处带血的脓包…… 初始之章·张勋 以下内容为张勋视角 年9月15日...
    茶点故事阅读 37,592评论 2 333
  • 正文 我和宋清朗相恋三年,在试婚纱的时候发现自己被绿了。 大学时的朋友给我发了我未婚夫和他白月光在一起吃饭的照片。...
    茶点故事阅读 39,764评论 1 348
  • 序言:一个原本活蹦乱跳的男人离奇死亡,死状恐怖,灵堂内的尸体忽然破棺而出,到底是诈尸还是另有隐情,我是刑警宁泽,带...
    沈念sama阅读 35,460评论 5 344
  • 正文 年R本政府宣布,位于F岛的核电站,受9级特大地震影响,放射性物质发生泄漏。R本人自食恶果不足惜,却给世界环境...
    茶点故事阅读 41,070评论 3 327
  • 文/蒙蒙 一、第九天 我趴在偏房一处隐蔽的房顶上张望。 院中可真热闹,春花似锦、人声如沸。这庄子的主人今日做“春日...
    开封第一讲书人阅读 31,697评论 0 22
  • 文/苍兰香墨 我抬头看了看天上的太阳。三九已至,却和暖如春,着一层夹袄步出监牢的瞬间,已是汗流浃背。 一阵脚步声响...
    开封第一讲书人阅读 32,846评论 1 269
  • 我被黑心中介骗来泰国打工, 没想到刚下飞机就差点儿被人妖公主榨干…… 1. 我叫王不留,地道东北人。 一个月前我还...
    沈念sama阅读 47,819评论 2 370
  • 正文 我出身青楼,却偏偏与公主长得像,于是被迫代替她去往敌国和亲。 传闻我的和亲对象是个残疾皇子,可洞房花烛夜当晚...
    茶点故事阅读 44,665评论 2 354

推荐阅读更多精彩内容

  • 设原始数据规模为n,需要采样的数量为k 先选取数据流中的前k个元素,保存在集合A中; 从第j(k + 1 <= j...
    Impossible安徒生阅读 290评论 0 0
  • 他人的整理与总结: https://leetcode.wang/ 1. & 15. K-sum 问题 此类问题的解...
    oneoverzero阅读 1,844评论 0 1
  • 一、链表问题 链表问题一定要进行举例画图,辅助思考!使用快慢指针遍历链表。因为链表无法得知长度,所以尝试用这种方法...
    voidFan阅读 290评论 0 1
  • 七.数组 1.给定一个整数数组 nums和一个目标值 target,请你在该数组中找出和为目标值的那两个整数,并返...
    寒江_d764阅读 282评论 0 0
  • 目录 1 左神部分集锦 2 Leetcode前150题 3 牛客网剑指offer 4 JavaG 5 题目中的...
    小小千千阅读 992评论 0 0