买苹果( 网易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;}







原创粉丝点击