1. 有1分,2分,5分,10分四种硬币,每种硬币数量无限,给定n分钱,求有多少种组合可以组合成n分钱?
#include <iostream>
#include <vector>
using namespace std;
int counts = 0; //统计组合方式数
int Target = 0;//存储需要组合的数
int coin[4] = {1,2,5,10}; //硬币的面值种类
int total = 0; //组合数当前的和
vector<int> solution; //存储组合方案
void dfs(int index)
{
if(total == Target)
{
counts++;
cout << counts << ":";
for(vector<int>::iterator iter = solution.begin(); iter != solution.end(); ++iter)
{
cout << *iter << " ";
}
cout << endl;
return ;
}
if(total > Target)
return ;
for(int i = index; i < 4; ++i)
{
total += coin[i];
solution.push_back(coin[i]);
dfs(i);
solution.pop_back();
total -= coin[i];
}
}
int main()
{
counts = 0;
cin >> Target;
dfs(0);
cout << counts << endl;
system("pause");
return 0;
}
2. 马戏团里有个叠罗汉的表演,为了便于美观,下面的人身高和体重都要大于上面的人。现在知道n个演员的身高和体重,请问最多能叠多少层?
3.Fibonacci数列中,一个Fibonacci数如果与它之前的Fibonacci数均互质,则称为Fibonacci质数。第一个Fibonacci质数为2,第二个为3,第三个为5。。。(Fibonacci数列为1, 1, 2, 3, 5, ...)。输入一个数K,则第K个Fibonacci质数所对应的序数是多少?
#include <iostream>
#include <vector>
using namespace std;
int gcd(int x, int y)
{
if(y == 0)
return x;
else
return gcd(y, x%y);
}
int find_fabo(int k)
{
int pre1, pre2, cur, cnt, index;
pre1 = 1;
pre2 = 1;
cnt = 0;
index = 2;
vector<int> ivec;
bool isNum = true;
while(true)
{
cur = pre1 + pre2;
index++;
if(!ivec.empty())
{
for(vector<int>::iterator iter = ivec.begin(); iter != ivec.end(); ++iter)
{
if(gcd(*iter, cur) != 1)
{
isNum = false;
break;
}
}
}
if(isNum)
{
cnt++;
if(cnt == k)
break;
}
ivec.push_back(cur);
pre1 = pre2;
pre2 = cur;
isNum = true;
}
return index;
}
int main()
{
cout << find_fabo(4) << endl;
return 0;
}
4.写一个函数: int print_num(int k){}; 要求函数功能为打印k的降序,直到0结束,即如果k=5,即打印: 5 4 3 2 1 0 要求: 不能用 if , if else, switch, ?: , while, for , do while, goto 语句
递归即可解决(当n为0时停止递归):
int printk(int n)
{
cout << n << ' ';
n && printk(n-1);
return n;
}
5.判断一个字符串是否为合法的十进制点IPv4地址,比如192.168.1.2
bool judge(const char *ip)
{
if(ip == NULL || ip[0] == '\0')
return false;
char str[4][20];
memset(str, '\0', sizeof(str));
int i = 0;
int dotCount = 0;
int j = 0;
while(ip[i] != '\0')
{
if(ip[i] == '.')
{
i++;
j = 0;
dotCount++;
if(dotCount > 3)
return false;
}
else
{
if(ip[i] < '0' || ip[i] > '9')
return false;
else
str[dotCount][j++] = ip[i++];
}
}
for(int k = 0; k < 4; k++)
{
if(strlen(str[k]) == 0 || atoi(str[k]) < 0 || atoi(str[k]) > 255)
return false;
}
return true;
}
int main(int argc, char *argv[])
{
char ip[100] = {'\0'};
while(cin >> ip)
{
if(judge(ip))
cout << "Yes" << endl;
else
cout << "No" << endl;
memset(ip, '\0', 100);
}
return 0;
}
6.输入一个正整数,若该数能用几个连续正整数之和表示,则输出所有可能的正整数序列。
void find_sequence(int num)
{
if(num <= 2)
{
return ;
}
int end = num/2 + 1;
int low = 1;
int high = 1;
int sum = 0;
while(low <= end)
{
sum = 0;
for(int i = low; i <= high; i++)
sum += i;
if(sum == num)
{
for(int i = low; i <= high; i++)
cout << i << " ";
cout << endl;
high++;
}
else if(sum > num)
low++;
else
high++;
}
}