LeetCode题目-40

首页 编程分享 LEET_CODE 正文

leetCode 转载 编程分享 2022-02-20 00:50:49

简介 LeetCode题目-40


✏Leetcode之PHP版题目解析(40. Combination Sum II)


✏描述

给定一个数组和一个目标数,求所有加起来等于目标数的组合,这个39题的第二版。它的规则和39有一点不同的是每一个结果集中目标的数只能使用一次,不能重复的使用。


✏题目实例


✏题目分析

这里我们还是可以复用39的code,只需要在代码中把重复的结果,以及数字复用的的情况处理一下即可。

✏解法一

       /**
            * @param Integer[] $candidates
            * @param Integer $target
            * @return Integer[][]
            */
           function combinationSum2($candidates, $target) {
               sort($candidates);
               $res=[];
               $out=[];
               $this->helper($candidates,$target,0,$out,$res);
               return $res;
           }
           
           function helper($candidates,$target,$index,&$out,&$res)
           {
               if($target<0) return ;
               if($target==0) {
                    array_push($res,$out); 
                   return ;
               }
               
               for($i=$index;$i < count($candidates);$i++){
                   if($i>$index && $candidates[$i]==$candidates[$i-1]) continue;
                   array_push($out,$candidates[$i]);
                   $this->helper($candidates,$target-$candidates[$i],$i+1,$out,$res);
                   array_pop($out);
               }
            }

转载链接:https://leetcode.cn/


Tags:


本篇评论 —— 揽流光,涤眉霜,清露烈酒一口话苍茫。


    声明:参照站内规则,不文明言论将会删除,谢谢合作。


      最新评论




ABOUT ME

Blogger:袅袅牧童 | Arkin

Ido:PHP攻城狮

WeChat:nnmutong

Email:nnmutong@icloud.com

标签云