【发布时间】:2013-07-30 04:48:59
【问题描述】:
我们有 7 件衬衫以随机顺序排列,例如 3 4 5 7 1 6 2。 我们可以对它们执行 4 次操作。 在每次操作中,将脱下的衬衫放入制作的间隙中。
- 取下中间的衬衫并将相邻的 3 件衬衫向右移动。
- 取下中间的衬衫,将相邻的 3 件衬衫向左移动。
- 移除最左边的衬衫并将相邻的 3 件衬衫移至左侧。
- 移除最右边的衬衫并将相邻的 3 件衬衫移至右侧。
给定 7 件衬衫以随机顺序排列,找出将衬衫按顺序排列所需的最少操作次数,即 1 2 3 4 5 6 7。
我尝试了一个使用排列的解决方案,但超过 7 次操作都失败了。
这是我的解决方案:
import java.util.*;
类衬衫2 {
public static void main(String[] ar)
{
Scanner sc = new Scanner(System.in);
String n = sc.next();
if(n.equals("1234567"))
{
System.out.println("0");
System.exit(0);
}
for(int i = 1; ; i++)
{
PermutationsWithRepetition gen = new PermutationsWithRepetition("1234",i);
List<String> v = gen.getVariations();
for(String j : v)
{
String t = n;
for(int k = 0;k < j.length(); k++)
{
int l = j.charAt(k) - '0';
t = operation(t,l);
}
if(t.equals("1234567"))
{
System.out.println(i + "\t" + j);
System.exit(0);
}
}
}
}
public static String operation(String t, int l)
{
if(l == 1)
return "" + t.charAt(3) + t.substring(0,3) + t.substring(4);
else if(l == 2)
return t.substring(0,3) + t.substring(4) + t.charAt(3);
else if(l == 3)
return t.substring(1,4) + t.charAt(0) + t.substring(4);
else
{
return t.substring(0,3) + t.charAt(6) + t.substring(3,6);
}
}
}
public class PermutationsWithRepetition {
private String a;
private int n;
public PermutationsWithRepetition(String a, int n) {
this.a = a;
this.n = n;
}
public List<String> getVariations() {
int l = a.length();
int permutations = (int) Math.pow(l, n);
char[][] table = new char[permutations][n];
for (int x = 0; x < n; x++) {
int t2 = (int) Math.pow(l, x);
for (int p1 = 0; p1 < permutations;) {
for (int al = 0; al < l; al++) {
for (int p2 = 0; p2 < t2; p2++) {
table[p1][x] = a.charAt(al);
p1++;
}
}
}
}
List<String> result = new ArrayList<String>();
for (char[] permutation : table) {
result.add(new String(permutation));
}
return result;
}
public static void main(String[] args) {
PermutationsWithRepetition gen = new PermutationsWithRepetition("abc", 3);
List<String> v = gen.getVariations();
for (String s : v) {
System.out.println(s);
}
}
【问题讨论】:
-
你尝试过什么递归解决方案?它的失败有多严重?请更新您的问题并提供更多详细信息。
-
发布您迄今为止尝试过的代码将使我们能够更好地帮助您,也将展示您的努力!!
-
如果你打算用蛮力来做,只需用四路节点制作一棵树,其中每路代表一种方法。如果您在其中一个节点上遇到答案,请将其打印出来。如果您跟踪迭代,您就知道它执行了多少步,如果您跟踪路径,您就知道它使用了哪些操作。
-
@bas 你甚至可以为此使用 fork-join。
标签: java algorithm brute-force