买苹果( 网易2017秋招编程题集合)
来源:互联网 发布:阿里云app名师课堂 编辑:程序博客网 时间:2024/05/17 06:01
小易去附近的商店买苹果,奸诈的商贩使用了捆绑交易,只提供6个每袋和8个每袋的包装(包装不可拆分)。 可是小易现在只想购买恰好n个苹果,小易想购买尽量少的袋数方便携带。如果不能购买恰好n个苹果,小易将不会购买。
输入一个整数n,表示小易想购买n(1 ≤ n ≤ 100)个苹果
输出一个整数表示最少需要购买的袋数,如果不能买恰好n个苹果则输出-1
本题可采用回溯法或者DP算法实现,下面附上代码
回溯法
#include<iostream>using namespace std;void backTrack(int& res, int count, int n) {if (n == 0) {if (res>count) {res = count;}return;}int arr[2] = { 6,8 };for (int i = 0; i<2; i++) {if (n >= arr[i]) {count++;backTrack(res, count, n - arr[i]);count--;}}}int main() {int n;cin >> n;int res = 100;backTrack(res, 0, n);if (res == 100) {cout << -1;}else {cout << res;}return 0;}
DP
#include<iostream>#include<vector>#include<algorithm>using namespace std;int main() {int n;cin >> n;vector<int> dp(n + 1, n);dp[0] = 0;vector<int> path = { 6,8 };for (int i = 0; i <= n; i++) {for (int j = 0; j<2; j++) {if (i + path[j] <= n) {dp[i + path[j]] = min(dp[i] + 1, dp[i + path[j]]);}}}if (dp[n] == n) {cout << -1;}else {cout << dp[n];}return 0;}
阅读全文
0 0
- 买苹果( 网易2017秋招编程题集合)
- 网易2017秋招编程题之买苹果
- 网易2017秋招编程题 买苹果
- 网易2017秋招编程题:买苹果 [python]
- 网易2017秋招编程题集合
- 网易2017秋招编程题集合
- 网易2017秋招编程题集合
- 网易2017秋招编程题集合
- 网易2017秋招编程题集合
- 网易2017秋招编程题集合
- 网易2017秋招编程题集合
- 《网易编程题》买苹果
- 网易2017春招编程题集合
- 网易2017秋招编程题集合-解题报告
- 【牛客网】网易2017秋招编程题集合
- 跳石板( 网易2017秋招编程题集合)
- 网易2017秋招编程题集合--完全解析
- 买苹果_网易编程
- Redis和Memcached的区别
- mac图片格式转换CR2->jpg
- Android开发者指南-运动传感器Motion Sensor
- Systick
- 二分检索及三分检索
- 买苹果( 网易2017秋招编程题集合)
- leetcode
- [CQOI2010] BZOJ 1816 扑克牌
- iOS UI代码片段-UIViewController present viewController 低下vc不消失
- oracle 将多条记录拼接成一个字符串
- centos7.3+nginx1.8+php7.1+mysql5.7 安装(二安装php)
- 循环冗余校验码CRC
- Centos7——selinux配置
- Linux下解压文件名乱码问题