@XQF
2018-03-07T22:59:50.000000Z
字数 1180
阅读 688
数据结构与算法
问题描述:针对1,2,2,3,4,5这几个数字,要求打印出所有排列,但是4不能在第三位,3和5不能相连。
[TOC]
public void print(int[] nums) {
int[] book = new int[nums.length];
int[] result = new int[nums.length];
int step = 0;
dfs(nums, result, book, step);
}
public void dfs(int[] nums, int[] result, int[] book, int step) {
if (step == book.length) {
System.out.println("nums:" + Arrays.toString(result));
return;
}
for (int i = 0; i < nums.length; i++) {
if (book[i] == 0) {
book[i] = 1;
result[step] = nums[i];
dfs(nums, result, book, step + 1);
book[i] = 0;
}
}
}
肯定是把条件直接加在输出就可以了
public class Solution {
public void print(int[] nums) {
int[] book = new int[nums.length];
int[] result = new int[nums.length];
int step = 0;
dfs(nums, result, book, step);
}
public void dfs(int[] nums, int[] result, int[] book, int step) {
if (step == book.length) {
boolean ok = true;
if (result[2] == 4) {
ok = false;
}
for (int i = 0; i < result.length - 1; i++) {
if (result[i] == 3 && result[i + 1] == 5) {
ok = false;
}
if (result[i] == 5 && result[i + 1] == 3) {
ok = false;
}
}
if (ok) {
System.out.println("result:" + Arrays.toString(result));
}
return;
}
for (int i = 0; i < nums.length; i++) {
if (book[i] == 0) {
book[i] = 1;
result[step] = nums[i];
dfs(nums, result, book, step + 1);
book[i] = 0;
}
}
}
public static void main(String[] args) {
Solution solution = new Solution();
int[] nums = {1, 2, 2, 3, 4, 5};
solution.print(nums);
}
}