recursion problem(IsMeasurable)(Is this correct?)
2015-05-31 21:12
295 查看
#include <iostream> #include <iomanip> #include <string> using namespace std; bool IsMeasurable(int target, int weights[], int nWeights); void SwapArray(int weights[], int i, int j); int main() { int sampleWeights[] = { 1, 3 }; int nSampleWeights = 2; cout << boolalpha; cout << IsMeasurable(2, sampleWeights, nSampleWeights) << endl; cout << IsMeasurable(5, sampleWeights, nSampleWeights) << endl; return 0; } bool IsMeasurable(int target, int weights[], int nWeights) { // simple case if (target == 0 && nWeights == 0) { return true; } if ((target == 0 && nWeights != 0) || (target != 0 && nWeights == 0)) { return false; } // recursive decomposition for (int i = 0; i < nWeights; i++) { int weight = weights[i]; SwapArray(weights, i, nWeights-1); if (IsMeasurable(target-weight, weights, nWeights-1) || IsMeasurable(target, weights, nWeights-1) || IsMeasurable(target + weight, weights,nWeights-1)) { return true; } SwapArray(weights, i, nWeights-1); } return false; } void SwapArray(int weights[], int i, int j) { int temp = weights[i]; weights[i] = weights[j]; weights[j] = temp; }
相关文章推荐
- 关于Android中ScrollView嵌套ListView的问题
- 链表综合算法设计
- 图的广度优先遍历
- JavaScript 简介
- 如何通过excel实现用户权限控制
- PPPOE on cisco router
- tableView中cell的删除、插入、移动、复制粘贴问题详解代码分析
- android基本架构
- Java常见的排序
- 第十章
- Fiddler进行手机抓包
- JAVA基础笔记——集合框架
- 单调递增子序列(优化)
- SSO(单点登录)—CAS总结
- android 数据存储简介
- SVN代码管理
- JAVA 一个特殊的类 Object
- nodejs+express+mongodb简单的例子
- HDU 4190 Distributing Ballot Boxes【二分答案】
- 阿里实习日记