using System; using System.Collections.Generic; using System.ComponentModel; using System.Data; using System.Drawing; using System.Linq; using System.Text; using System.Windows.Forms;
namespace WindowsFormsApplication1 { public partial class Form1 : Form { public Form1() { InitializeComponent(); }
string lastStr; string xx; int num; int count;
private void button1_Click(object sender, EventArgs e) { count = 0; this.label1.Text = ""; textBox2.Clear(); num = Convert.ToInt32(textBox1.Text.Trim()); run(); label1.Text = "种共有【" + count.ToString() + "】种算法"; } void run() { lastStr = ""; for (int i1 = 0; i1 <= 1; i1++) for (int i2 = 0; i2 <= 1; i2++) for (int i3 = 0; i3 <= 1; i3++) for (int i4 = 0; i4 <= 1; i4++) for (int i5 = 0; i5 <= 1; i5++) for (int i6 = 0; i6 <= 1; i6++) for (int i7 = 0; i7 <= 1; i7++) for (int i8 = 0; i8 <= 1; i8++) for (int i9 = 0; i9 <= 1; i9++) { lastStr = i1.ToString() + i2.ToString() + i3.ToString() + i4.ToString() + i5.ToString() + i6.ToString() + i7.ToString() + i8.ToString() + i9.ToString(); zhuanhua(); } }
public void zhuanhua() { string starstr = "123456789"; for (int ii = 0; ii < 9; ii++) { string x = lastStr.Substring(ii, 1); string y = starstr.Substring(ii, 1); if (x == "1") { xx = xx + y; } } if (xx == null) return; panduan(); }
public void panduan() { int tt = 0; string pp = ""; for (int i = 0; i < xx.Length; i++) { string x = xx.Substring(i, 1); pp = x + "+" + pp; int xxx = Convert.ToInt32(x); tt = tt + xxx; } if (tt == num) { pp = pp.Substring(0, pp.Length - 1); textBox2.AppendText(pp + "=" + tt + " "); count++; } else { xx = ""; } } } }
能否先把1-9的数加起来所有情况都列出来,然后看结果是5的有多少
可以上面的代码、可以实现功能、你可以看看、在把你的想法进行实现。应该就行了 。谢。。
@枫林海: 嘿嘿点错了
已经有人问过了:http://q.cnblogs.com/q/33111/
谢谢你的提醒、我会去看的。不过那个好像是(A=A+B的模式、我要的是A=b+c、A=B+c+d、A=B+c+d+e、A=B+c+d+e+...的都可以)
@枫林海: 看清楚,都可以的。其中有个答案是我回答的,我能不知道么。。。
递归:http://jsfiddle.net/FnENA/
var s = "";
function getSumMethods(n,prev)
{
if (n<=0)
{
s += prev.join("+") + "\n";
return prev;
}
var i;
for(i=1;i<=n;++i)
{
var cloned = prev.slice();
cloned.push(i);
getMethods(n-i,cloned);
}
}
getSumMethods(9,[]);
alert(s)