LeetCode题目-39

首页 编程分享 LEET_CODE 正文

leetCode 转载 编程分享 2017-12-20 18:54:45

简介 LeetCode题目-39


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


✏描述

给定一个数组和一个目标数,求所有加起来等于目标数的组合,注意一个数可以被多次利用,但是组合是唯一的,不能有重复的组合。


✏题目实例


✏题目分析

这里我定义了三个变量,用来记录当前递归的数组下标,每次产生一个结果的小集合,以及最终所有符合条件的集合,返回的也就是一个二维数组.

✏解法一

        /**
           * @param Integer[] $candidates
           * @param Integer $target
           * @return Integer[][]
           */
          function combinationSum($candidates, $target) {
              $out=[];
              $res=[];
             $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++){
                  array_push($out,$candidates[$i]);
                  $this->helper($candidates,$target-$candidates[$i],$i,$out,$res);
                  array_pop($out);
              }
          }

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


Tags:


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


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


      最新评论




ABOUT ME

Blogger:袅袅牧童 | Arkin

Ido:PHP攻城狮

WeChat:nnmutong

Email:nnmutong@icloud.com

标签云