买苹果( 网易2017秋招编程题集合)
2017-06-11 19:54
369 查看
小易去附近的商店买苹果,奸诈的商贩使用了捆绑交易,只提供6个每袋和8个每袋的包装(包装不可拆分)。 可是小易现在只想购买恰好n个苹果,小易想购买尽量少的袋数方便携带。如果不能购买恰好n个苹果,小易将不会购买。
本题可采用回溯法或者DP算法实现,下面附上代码
回溯法
DP
输入一个整数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) { cout << -1; } else { cout << dp ; } return 0; }
相关文章推荐
- 网易2017秋招编程题集合--完全解析
- 网易2017春招编程题集合
- 【牛客网】网易2017秋招编程题集合
- 网易2017秋招编程题集合
- 网易2017秋招编程题集合
- 网易2017春招编程题:集合 [python]
- 网易2017秋招编程题集合
- 网易2017秋招编程题集合
- 牛客网-网易2017秋招编程题集合-解题思路及源码
- 网易2017秋招编程题集合-解题报告
- 网易2017秋招编程题集合
- 2017网易内推编程题(测试工程师)--分苹果
- 跳石板( 网易2017秋招编程题集合)
- 网易2017内推面试题-分苹果
- 网易2017秋招编程题8
- 网易2017内推笔试编:分苹果
- 买苹果_网易编程
- 网易2017校招编程:计算糖果
- 网易2017秋招编程
- 网易2017校园招聘编程题——分苹果