博客
关于我
强烈建议你试试无所不能的chatGPT,快点击我
BackTracking_Fixed sum for array elements
阅读量:6117 次
发布时间:2019-06-21

本文共 1582 字,大约阅读时间需要 5 分钟。

Given an array a contains distinct positive integers, count how many combinations of integers in a add up to exactly sum

For example, given int[] a = {11, 3, 8} ; and sum = 11

You should output 2, because 11 == 11 and 3 + 8 == 11

This is typically a backtracking problem

Enumerate all the subsets of the given array to see how many of them match the condition

when you write backtracking procedure using recursion, please be careful of which condition do you

use to terminate the loop, in this code snippet, there two conditions,

1. sum == 0

2. t == a.Length

and when t == a.Length, we might be got an solution yet, don't forget this case.

Backtracking

Code

recursive way

Code

C法

#include
#include
int count = 0; // number of solutions/* * array - positive numbers * n - element count in array * sum - pair of sum * t - recursion deep */void find_combinations(int *array, int n, int sum, int t) { if (t == n) { if (sum == 0) { count++; } return; } if (sum == 0) { // Find a solution count++; } else { if (sum >= array[t]) { // left tree find_combinations(array, n, sum - array[t], t + 1); } if (sum > 0) { // right tree find_combinations(array, n, sum, t + 1); } }}int main(void) { int a[] = {
11, 3, 8, 4, 1, 7}; find_combinations(a, 6, 11, 0); printf("%d\n", count); system("pause"); return 0;}

==

本文转自zdd博客园博客,原文链接:http://www.cnblogs.com/graphics/archive/2009/06/03/1495466.html,如需转载请自行联系原作者

你可能感兴趣的文章
User implements HttpSessionBindingListener
查看>>
抽象工厂方法
查看>>
ubuntu apt-get 安装 lnmp
查看>>
焊盘 往同一个方向增加 固定的长度方法 总结
查看>>
eclipse的maven、Scala环境搭建
查看>>
架构师之路(一)- 什么是软件架构
查看>>
jquery的冒泡和默认行为
查看>>
USACO 土地购买
查看>>
【原创】远景能源面试--一面
查看>>
B1010.一元多项式求导(25)
查看>>
10、程序员和编译器之间的关系
查看>>
前端学习之正则表达式
查看>>
配置 RAILS FOR JRUBY1.7.4
查看>>
AndroidStudio中导入SlidingMenu报错解决方案
查看>>
修改GRUB2背景图片
查看>>
Ajax异步
查看>>
好记性不如烂笔杆-android学习笔记<十六> switcher和gallery
查看>>
JAVA GC
查看>>
codeforce 599B Spongebob and Joke
查看>>
3springboot:springboot配置文件(外部配置加载顺序、自动配置原理,@Conditional)
查看>>