[关闭]
@XQF 2018-03-07T22:59:50.000000Z 字数 1180 阅读 688

如何按要求打印数组的排列情况?

数据结构与算法


问题描述:针对1,2,2,3,4,5这几个数字,要求打印出所有排列,但是4不能在第三位,3和5不能相连。
[TOC]

1.数组全排列dfs

  1. public void print(int[] nums) {
  2. int[] book = new int[nums.length];
  3. int[] result = new int[nums.length];
  4. int step = 0;
  5. dfs(nums, result, book, step);
  6. }
  7. public void dfs(int[] nums, int[] result, int[] book, int step) {
  8. if (step == book.length) {
  9. System.out.println("nums:" + Arrays.toString(result));
  10. return;
  11. }
  12. for (int i = 0; i < nums.length; i++) {
  13. if (book[i] == 0) {
  14. book[i] = 1;
  15. result[step] = nums[i];
  16. dfs(nums, result, book, step + 1);
  17. book[i] = 0;
  18. }
  19. }
  20. }

2.做手脚

肯定是把条件直接加在输出就可以了

  1. public class Solution {
  2. public void print(int[] nums) {
  3. int[] book = new int[nums.length];
  4. int[] result = new int[nums.length];
  5. int step = 0;
  6. dfs(nums, result, book, step);
  7. }
  8. public void dfs(int[] nums, int[] result, int[] book, int step) {
  9. if (step == book.length) {
  10. boolean ok = true;
  11. if (result[2] == 4) {
  12. ok = false;
  13. }
  14. for (int i = 0; i < result.length - 1; i++) {
  15. if (result[i] == 3 && result[i + 1] == 5) {
  16. ok = false;
  17. }
  18. if (result[i] == 5 && result[i + 1] == 3) {
  19. ok = false;
  20. }
  21. }
  22. if (ok) {
  23. System.out.println("result:" + Arrays.toString(result));
  24. }
  25. return;
  26. }
  27. for (int i = 0; i < nums.length; i++) {
  28. if (book[i] == 0) {
  29. book[i] = 1;
  30. result[step] = nums[i];
  31. dfs(nums, result, book, step + 1);
  32. book[i] = 0;
  33. }
  34. }
  35. }
  36. public static void main(String[] args) {
  37. Solution solution = new Solution();
  38. int[] nums = {1, 2, 2, 3, 4, 5};
  39. solution.print(nums);
  40. }
  41. }
添加新批注
在作者公开此批注前,只有你和作者可见。
回复批注