回溯法应用:整数拆分
来源:互联网 发布:手机淘宝店铺上货教程 编辑:程序博客网 时间:2024/05/16 10:08
题目
笔试的时候遇到这么一个问题:
6 = 1+1 +1+ 1+ 1 +1
6 = 1+ 1+ 1+ 1+ 2
6 = 1+ 1+ 1+ 3
6 = 1+ 1+ 2+ 2
6 = 1+ 1+ 4
6 = 1+ 2+ 3
6 = 1+ 5
6 = 2+ 2+ 2
6 = 2+ 4
6 = 3+ 3
6 = 6
就这样,给定一个数,打印出这种形式
分析
递归,回溯。
代码
#include<iostream>#include<vector>using namespace std;void print(int n, vector<int> &re){ if(n < 0) return; if(n == 0){ for(auto i : re){ cout << i << " "; } cout << endl; } else{ int start = 1; int length = re.size(); if(length != 0) start = re.at(length - 1); for(int i = start; i <= n; i++){ re.push_back(i); print(n - i, re); re.pop_back(); } }}int main(){ vector<int> re; print(6, re); return 0;}
0 0
- 回溯法应用:整数拆分
- 整数拆分-递归法
- 整数变换问题-----回溯法
- 整数拆分
- 整数拆分
- 整数拆分
- 整数拆分
- 整数拆分
- 整数拆分
- 整数拆分
- 整数拆分
- 拆分整数
- 整数拆分
- 整数拆分
- 整数拆分
- 整数拆分
- 整数拆分
- 回溯法及其应用
- Seeding
- 打开系统设置界面
- 对字典进行排序
- 深入浅出Gradle 整理
- Spring JdbcTemplate笔记
- 回溯法应用:整数拆分
- 为什么选择Nginx
- Avoid The Lakes
- 如何加密文件夹
- jQuery 参考手册 - 选择器
- Object分析--1、clone()方法
- Block使用详解,Block与代理相比的优点与缺点
- Java8中用sun.misc.Contended避免伪共享(false sharing)
- AVL