读书人

这个回望错哪部了

发布时间: 2012-12-26 14:39:29 作者: rapoo

这个回溯错哪部了?

public class t1491 {
static int a[] = new int[3] ;
static int f[] = new int[3];

public static void main(String[] args) {
// TODO Auto-generated method stub
backtrack(0);
}
public static void backtrack(int depth)
{
if(depth==a.length)
{
for(int i=0; i<a.length;i++)
{
System.out.print(a[i]);
}
System.out.println();
}
for(int i=0;i<a.length;i++)
{
if(f[i]==0)
{
a[i]=i+1;
f[i]=1;
backtrack(depth+1);
f[i]=0;
}
}
}

}

为什么输出都是123?
[最优解释]
引用:
引用:按照你的代码结果就是这样6行1 2 3,三个数,第一个从i=0开始后,第二个数i=1的考虑过后,应该考虑i=2,但你的a[1]=2,还是没变,相当于你只操作了a[2],最外层i=0操作后,a[0]你还是没操作,保留了上次的结果,还是上个结果a[0]=1,所以你的回溯写的不对。
那应该怎样改?应该就一小点错了
……

不知道你想要什么结果,看下面的例子,自己想吧
#include <stdio.h>
int num[10];
int visit[10];
void dfs( int index ){
if( index==10 ){
int a = 100*num[1] + 10*num[2] + num[3];
int b = 100*num[4] + 10*num[5] + num[6];
int c = 100*num[7] + 10*num[8] + num[9];
if( a==2*b && a==3*c )
printf( "%d %d %d\n", a, b, c);
}
int i;
for( i=1; i<=9; i++){
if( visit[i]!=1 ){
visit[i]=1;
num[i] = index;
dfs(index+1); //深度搜索
visit[i] = 0; //回溯
}
}
}
int main (void)
{
int i;
for(i=0; i<10; i++)
visit[i] = 0;
dfs(1);
return 0;
}
//将1到9这九个数字分成3个三位数a,b,c,要求第1个三位数,正好是第2个三位数的两倍,是第3个三位数的三倍
[其他解释]
引用:
Java code
?



12345678910111213141516171819202122232425262728293031

public class t1491 { static int a[] = new int[3] ; static int f[] = new int[3]; public static void main(S……

顺便问一句如果位数变成n的话怎样写好 1<=n<=9
------其他解决方案--------------------


引用:
引用:
Java code
?



12345678910111213141516171819202122232425262728293031

public class t1491 { static int a[] = new int[3] ; static int f[] = new int[3]; pu……


这个问题你把声明放在外面,然后实例化放在构造器或者主函数里面。

比如
class a{
static int a[];
int n;
public void a(){
Scanner in=new Scanner(System.in);
n=in.nextInt;
a[] =new int[n];
}
}

[其他解释]
第一问,我费了好大劲才明白
你是不是想要
1
2
3
1
2
3
。。。
这样的效果?
for(int i=0; i<a.length;i++)
{
System.out.print(a[i]);
}
System.out.println();
改成
for(int i=0; i<a.length;i++)
{
System.out.println(a[i]);
}
如果理解错了,就说说你认为的应该是什么效果?然后回帖
[其他解释]
按照你的代码结果就是这样6行1 2 3,三个数,第一个从i=0开始后,第二个数i=1的考虑过后,应该考虑i=2,但你的a[1]=2,还是没变,相当于你只操作了a[2],最外层i=0操作后,a[0]你还是没操作,保留了上次的结果,还是上个结果a[0]=1,所以你的回溯写的不对。
[其他解释]
引用:
第一问,我费了好大劲才明白
你是不是想要
1
2
3
1
2
3
。。。
这样的效果?
for(int i=0; i<a.length;i++)
{
System.out.print(a[i]);
}
System.out.println();
改成
……

不是。。是
123
213
312.。。。。。那样所有组合
[其他解释]
引用:
按照你的代码结果就是这样6行1 2 3,三个数,第一个从i=0开始后,第二个数i=1的考虑过后,应该考虑i=2,但你的a[1]=2,还是没变,相当于你只操作了a[2],最外层i=0操作后,a[0]你还是没操作,保留了上次的结果,还是上个结果a[0]=1,所以你的回溯写的不对。

那应该怎样改?应该就一小点错了
[其他解释]
=》a[i]=i+1。。。

读书人网 >J2SE开发

热点推荐