嘿家伙。几个小时来我一直在努力解决回溯问题。任何人都可以借我一只手吗?问题如下:Java回溯问题
n
骆驼编号从1到n
是排列顺序。我想重新排列,这样每个骆驼在前面都有不同的骆驼。
这是我到目前为止有:
import java.util.*;
public class NCamile{
static int size;
static int count;
static char[] arrN= new char[100];
public static void main(String[] args){
System.out.print("Enter word: ");
String numar = getInt();
size = numar.length();
count=0;
for(int i=0; i < size ; i++){
arrN[i] = numar.charAt(i);
}
backtraking(size);
}
public static void backtraking(int newsize){
if (newsize == 1){
return;
}
for(int i=0 ; i < newsize; i++){
backtraking(newsize - 1);
if(newsize == 2){
display();
}
rotate(newsize);
}
}
public static void rotate(int newsize){
int position = size - newsize;
for(int i = position + 1; i < newsize; i++){
char gigi;
gigi = arrN[i - 1];
arrN[i - 1] = arrN [i];
arrN[i] = gigi;
}
}
public static void display(){
if (count < 9){
System.out.print(" ");
}
System.out.print(++count+ ")" + " ");
for(int i = 0 ; i < size ; i++)
System.out.print(arrN[i]);
System.out.print(" ");
if(count % 10 == 0){
System.out.println(" ");
}
}
public static String getInt(){
Scanner scan = new Scanner(System.in);
String s = scan.next();
return s;
}
}
这样,algorithems告诉我每更多钞票的解决方案重新安排一个字符串,但它这么想的尊重问题的最后一个条件。我试过ading这样的:
for(int j = 0 ; j < size ; j++){
if (array[j] !=[array[j + 1])
display()
}
但经过我说这我得到了约10倍的显示的单词,那么它应该显示我
谁能给我我该怎么办的想法?
“前面”是否意味着我们只需要将元素更改为左侧?在那种情况下,不会简单地颠倒阵列就会得出答案? – MAK
没有那个算法必须显示每一个可能的结果。例如,让我们取这个数字:1234下一次显示2不能在1前面3不能在2前面和4前面不能在3前面所以一个 – user846603
@MAK我们不得不倒转第一个元素的数组。因为他说“每个骆驼在前面都有不同的骆驼”。如果不是,最后一只骆驼在前面不会有骆驼。 (没有骆驼==不同的骆驼)是假的,我认为是。 –