看这个算式:
☆☆☆ + ☆☆☆ = ☆☆☆
如果每个五角星代表 1 ~ 9 的不同的数字。
这个算式有多少种可能的正确填写方法?
173 + 286 = 459
295 + 173 = 468
173 + 295 = 468
183 + 492 = 675
以上都是正确的填写法!
注意:
111 + 222 = 333 是错误的填写法!
因为每个数字必须是不同的!
也就是说:1~9中的所有数字,每个必须出现且仅出现一次!
结题思路:
排列1~9,写出符合条件的结果。
代码如下:


public class Main
{

static int bs[] =
{1, 2, 3, 4, 5, 6, 7, 8, 9};
static int count = 0;
public static void main(String[] args)

{
count = 0;
DFS(0);
System.out.println("count=" + count);
}

static void DFS(int nowp)
{

if(nowp == bs.length)
{
int n1 = bs[0] * 100 + bs[1] * 10 + bs[2];
int n2 = bs[3] * 100 + bs[4] * 10 + bs[5];
int n3 = bs[6] * 100 + bs[7] * 10 + bs[8];

if(n1 + n2 == n3)
{
System.out.println(n1 + " + " + n2 + " = " + n3);
count++;
}
}

else
{

for(int i = nowp; i < bs.length; i++)
{
swap(nowp, i);
DFS(nowp + 1);
swap(nowp, i);
}
}
}

static void swap(int a, int b)
{
int t = bs[a];
bs[a] = bs[b];
bs[b] = t;
}
}
posted on 2013-07-07 16:08
小鼠标 阅读(299)
评论(0) 编辑 收藏 引用 所属分类:
Java基础练习