我试图在java中置换一组点,其限制是奇数位置n中的所有点都不能出现在位置(n-1)之前,即,给定2点1和2,2之前不能出现1在任何排列和给定点1,2,3& 4,预期排列的集合是:
1,2,3,4
1,3,2,4
1,3,4,2
3,1,2,4
3,4,1,2
3,1,4,2
我目前有以下代码来查找排列:
static void permute(int[] a, int k,int[] p) {
if (k == a.length) {
for (int i = 0; i < a.length; i++) {
System.out.print(" " + a[i]);
}
System.out.println();
}
else {
int temp;
for (int i = k; i < a.length; i++) {
if(i % 2 == 0){
temp = a[k];
a[k] = a[i];
a[i] = temp;
permute(a, k + 1,p);
temp = a[k];
a[k] = a[i];
a[i] = temp;
}
else{
if(k > p[i]){
temp = a[k];
a[k] = a[i];
a[i] = temp;
permute(a, k + 1,p);
temp = a[k];
a[k] = a[i];
a[i] = temp;
}
}
}
}
}
但我目前的输出是:
1 2 3 4
1 2 4 3
1 3 2 4
1 3 4 2
1 4 3 2
1 4 2 3
3 2 1 4
3 2 4 1
3 1 2 4
3 1 4 2
3 4 1 2
3 4 2 1
任何帮助都会非常感激: - )
答案 0 :(得分:2)
您可以先找到所有排列,然后仅过滤那些遵守限制的排列。下面是一个例子:
import java.util.ArrayList;
import java.util.List;
public class PermutationsExample {
static int[] arr = {1,2,3,4};
public static void main(String[] args) {
List<List<Integer>> allPermutationList = getAllPermutations(arr);
System.out.println("All permutations are :");
System.out.println(allPermutationList);
System.out.println("");
List<List<Integer>> subPermutationList = getRestrictedPermutations(allPermutationList);
System.out.println("Permutations with restrictions are:");
System.out.println(subPermutationList);
}
// see http://www.programcreek.com/2013/02/leetcode-permutations-java/ for further info
public static List<List<Integer>> getAllPermutations(int[] num) {
List<List<Integer>> result = new ArrayList<>();
result.add(new ArrayList<>());
for (int i = 0; i < num.length; i++) {
List<List<Integer>> current = new ArrayList<>();
for (List<Integer> l : result) {
for (int j = 0; j < l.size()+1; j++) {
l.add(j, num[i]);
List<Integer> temp = new ArrayList<>(l);
current.add(temp);
l.remove(j);
}
}
result = new ArrayList<>(current);
}
return result;
}
public static List<List<Integer>> getRestrictedPermutations(List<List<Integer>> listofList){
List<List<Integer>> result = new ArrayList<>();
for(List<Integer> list: listofList){
if(isRestrictionRespected(list)){
result.add(list);
}
}
return result;
}
public static boolean isRestrictionRespected(List<Integer> list){
boolean result = true;
for (int i = 1; i < arr.length; i+=2 ) {
if(list.indexOf(arr[i])<list.indexOf(arr[i-1])){
result = false;
break;
}
}
return result;
}
}
答案 1 :(得分:1)
递归方法怎么样?
只要违反条件,就立即切断递归分支。