C语言练习 表达式的递归计算

在1 2 3 4 5 6 7 8 9 之间的8个空之间填入“+”“-”“ ”三种,使表达式的值为110。比如1 2之间填入的是“ ”,则他们成为12。8个都是“ ”则表达式的值为123456789。

输出所有的情况,使表达式的值为110。

#include <STDIO.H>
#include <string>
#include <stdlib.h>
using namespace std;
int total;

void print(string str)
{
	printf("%d:",total++);
	int i=0,len=str.length();
	while(i<len&&str[i]!='1') i++;
	for (;i<len;i++)
	{
		printf("%c",str[i]);
	}
	printf("=110\n");
}
string atos(int n)
{
	if (n==0)
	{
		return "0";
	}
	string str="";
	int N=1000000000;
	while (n/N==0)
	{
		N=N/10;
	}
	while (n>0)
	{
		str+=char('0'+n/N);
		n=n%N;
		N=N/10;
	}
	return str;
}
void function(int cur,int pre,string str,int result)
{
	if (result==110&&cur>10)
	{
		print(str);
	}
	else if (cur>10)
	{
		return;
	}
	else
	{
		function(cur+1,pre*10+cur,str,result);
		function(cur+1,cur,str+"+"+atos(pre),result+pre);
		function(cur+1,cur,str+"-"+atos(pre),result-pre);
	}

}

int main()
{
	function(0,0," ",0);
	return 0;
}


  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值