markdown 查找添加到给定数字的所有组合
Posted
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了markdown 查找添加到给定数字的所有组合相关的知识,希望对你有一定的参考价值。
Given a positive number, find out all combinations of positive numbers that adds upto that number. The program should print only combinations, not permutations. For example, for input 3, either 1, 2 or 2, 1 should be printed.
Examples :
```
Input: N = 3
Output:
1 1 1
1 2
3
```
```
Input: N = 5
Output:
1 1 1 1 1
1 1 1 2
1 1 3
1 2 2
1 4
2 3
5
```
The idea is to use recursion. We use an array to store combinations and we recursively fill the array and recurse with reduced number. The invariant used in the solution is that each combination will always be stored in increasing order of elements involved. That way we can avoid printing permutations.
Below is implementation of above idea :
```
<?php
// PHP program to find out all
// combinations of positive
// numbers that add upto given number
/* arr - array to store the combination
index - next location in array
num - given number
reducedNum - reduced number */
function findCombinationsUtil($arr, $index,
$num, $reducedNum)
{
// Base condition
if ($reducedNum < 0)
return;
// If combination is
// found, print it
if ($reducedNum == 0)
{
for ($i = 0; $i < $index; $i++)
echo $arr[$i] , " ";
echo "\n";
return;
}
// Find the previous number
// stored in arr[] It helps
// in maintaining increasing order
$prev = ($index == 0) ? 1 : $arr[$index - 1];
// note loop starts from previous
// number i.e. at array location
// index - 1
for ($k = $prev; $k <= $num ; $k++)
{
// next element of array is k
$arr[$index] = $k;
// call recursively with
// reduced number
findCombinationsUtil($arr, $index + 1,
$num, $reducedNum - $k);
}
}
/* Function to find out all
combinations of positive numbers
that add upto given number.
It uses findCombinationsUtil() */
function findCombinations($n)
{
// array to store the combinations
// It can contain max n elements
$arr = array();
//find all combinations
findCombinationsUtil($arr, 0, $n, $n);
}
```
```
// Driver code
$n = 5;
findCombinations($n);
// This code is contributed by ajit
?>
```
以上是关于markdown 查找添加到给定数字的所有组合的主要内容,如果未能解决你的问题,请参考以下文章