>  기사  >  백엔드 개발  >  PHP에서 역추적 알고리즘을 사용하여 결합 합계를 계산하는 방법

PHP에서 역추적 알고리즘을 사용하여 결합 합계를 계산하는 방법

醉折花枝作酒筹
醉折花枝作酒筹원래의
2021-07-13 15:16:591940검색

후보 배열과 목표 숫자 목표가 주어지면 숫자의 합이 목표가 될 수 있는 후보의 모든 조합을 찾으세요. 이때 우리는 무엇을 해야 합니까? 오늘은 그 내용을 안내해 드리겠습니다.

PHP에서 역추적 알고리즘을 사용하여 결합 합계를 계산하는 방법

배열 후보와 목표 숫자 목표가 주어지면 숫자 목표의 합을 만들 수 있는 후보의 모든 조합을 찾습니다.

후보자의 각 번호는 각 조합에 한 번만 사용할 수 있습니다.

참고:

모든 숫자(대상 숫자 포함)는 양의 정수입니다. 솔루션 세트에는 중복된 조합이 포함될 수 없습니다.

예 1:

输入: candidates = [10,1,2,7,6,1,5], target = 8,
所求解集为:[
 [1, 7],
 [1, 2, 5],
 [2, 6],
 [1, 1, 6]]

예 2:

输入: candidates = [2,5,2,1,2], target = 5,
所求解集为:[  
[1,2,2],  
[5]]

문제 해결 아이디어

역추적 알고리즘 그룹 제거 순열/조합/부분 집합 문제에 대한 직접 참조

code

class Solution {
    /** * @param Integer[] $candidates * @param Integer $target * @return Integer[][] */
    public $res = [];
    function combinationSum2($candidates, $target) {
        sort($candidates);   // 排序
        $this->dfs([], $candidates, $target, 0);
        return $this->res;
    }
    function dfs($array, $candidates, $target, $start) {
        if ($target < 0) return;
        if ($target === 0) {
            $this->res[] = $array;
            return;
        }
        $count = count($candidates);
        for ($i = $start; $i < $count; $i++) {
            if ($i !== $start && $candidates[$i] === $candidates[$i - 1]) continue;
            $array[] = $candidates[$i];
            $this->dfs($array, $candidates, $target - $candidates[$i], $i + 1);//数字不能重复使用,需要+1
            array_pop($array);
        }
    }}

추가:

중복된 요소가 없고 목표 숫자 목표가 있는 후보 배열이 주어지면 숫자의 합이 목표가 될 수 있는 후보의 모든 조합을 찾으세요.

후보자의 숫자는 제한 없이 반복해서 선택할 수 있습니다.

차이점은 반복선택이 허용된다는 점이며, 이전 질문을 바탕으로 두 가지를 변경하면 해결됩니다.

class Solution {
    /** * @param Integer[] $candidates * @param Integer $target * @return Integer[][] */
    public $res = [];
    function combinationSum($candidates, $target) {
        sort($candidates);   // 排序
        $this->dfs([], $candidates, $target, 0);
        return $this->res;
    }
    function dfs($array, $candidates, $target, $start) {
        if ($target < 0) return;
        if ($target === 0) {
            $this->res[] = $array;
            return;
        }
        $count = count($candidates);
        for ($i = $start; $i < $count; $i++) {
            // if ($i !== $start && $candidates[$i] === $candidates[$i - 1]) continue; // 注释掉去重的代码
            $array[] = $candidates[$i];
            $this->dfs($array, $candidates, $target - $candidates[$i], $i);//数字能重复使用, 不需要+1
            array_pop($array);
        }
    }}

추가:

합이 n인 k개의 숫자 조합을 모두 찾아보세요. 조합에는 1부터 9까지의 양의 정수만 허용되며, 각 조합에는 중복되는 숫자가 없습니다.

선택한 구성표의 요소 수를 제한하세요

class Solution {
    public $res = [];
    /** * @param Integer $k * @param Integer $n * @return Integer[][] */
    function combinationSum3($k, $n) {
        $this->dfs([], [1,2,3,4,5,6,7,8,9], $n, 0, $k);
        return $this->res;
    }
    function dfs($array, $candidates, $n, $start, $k) {
        if ($n < 0) return;
        if ($n === 0 && count($array) === $k) {
            $this->res[] = $array;
            return;
        }
        for ($i = $start; $i < 9; $i++) {
            if ($i !== $start && $candidates[$i] === $candidates[$i - 1]) continue;
            $array[] = $candidates[$i];
            $this->dfs($array, $candidates, $n - $candidates[$i], $i + 1, $k);
            array_pop($array);
        }
    }}

추천 학습: php 비디오 튜토리얼

위 내용은 PHP에서 역추적 알고리즘을 사용하여 결합 합계를 계산하는 방법의 상세 내용입니다. 자세한 내용은 PHP 중국어 웹사이트의 기타 관련 기사를 참조하세요!

성명:
본 글의 내용은 네티즌들의 자발적인 기여로 작성되었으며, 저작권은 원저작자에게 있습니다. 본 사이트는 이에 상응하는 법적 책임을 지지 않습니다. 표절이나 침해가 의심되는 콘텐츠를 발견한 경우 admin@php.cn으로 문의하세요.