您的位置:首页 > 编程语言

买苹果( 网易2017秋招编程题集合)

2017-06-11 19:54 369 查看
小易去附近的商店买苹果,奸诈的商贩使用了捆绑交易,只提供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)
{
cout << -1;
}
else
{
cout << dp
;
}
return 0;
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  回溯法 DP