基础-简单的深度优先遍历

输出1,2,3,4,5,6,7 这几个数组成的全排列

  ps:可以使用枚举(但是需要7层循环)

使用递归(深度优先遍历的思路,DFS也可利用栈数据结构来实现,LIFO)

package com.nxz.blog.otherTest;

/**
 * 简单的深度优先遍历算法学习
 */
public class Test03 {

    /**
     * 输出1,2,3,4,5,6,7的全排列
     * 可以将问题形象化,也就是说:将以上几个数放到7个空的位置 □ □ □ □ □ □ □ ,使用一个变量来表示当前处理的是第几个框,
     * 使用一个长度为7的数组来表示一个数是否已经放置过了
     * 当处理当前框的时候,需要考虑当前位置可以放置的值有哪些(也就是进行遍历操作),
     * 当前step处理完成时候,step+1,处理下一个框,下一个框的出来过程和当前处理过程一样(也就是使用递归)
     *
     * @param args
     */
    public static void main(String[] args) {

        deepFirstSearch(new int[]{1, 2, 3, 4, 5, 6, 7}, 0);
        System.out.println("共有组合个数:" + sum);
    }

    private static int[] book = new int[10];
    private static int[] res = new int[7];
    private static int sum;

    //最开始处理step以0开始
    public static void deepFirstSearch(int[] arr, int step) {

        //递归的终止条件
        if (step == arr.length) {
            for (int re : res) {
                System.out.print(re);
            }
            System.out.println();
            sum++;
            return;
        }

        //当前框时,可以放置那些值
        for (int val : arr) {
            //表示当前数还没有放置过
            if (book[val] == 0) {
                //将当前值标记为已放置
                book[val] = 1;
                //将arr[i]放入当前位置
                res[step] = val;
                //处理下一个框step+1
                deepFirstSearch(arr, step + 1);
                //处理完毕后经单签book[i]复原
                book[val] = 0;
            }
        }
        return;
    }
}

输出:

1234567
1234576
1234657
1234675
1234756
1234765
1235467
1235476

。。。。。

共有组合个数:5040

或者是有1-9,9个数字,把9个数字填入以下方格,并且每一个方格的数字都不同,使等式成立  □□□ + □□□ = □□□

这个问题可以用上边的代码,只是将判断终止条件修改下,在终止时,判断(100*方块1 + 10 * 方块2 + 方块3 )+ (100 * 方块4 + 10 * 方块5 + 方块6) = =100 * 方块7 + 10 * 方块8 + 方块9

如果等式成立则输出 等式,不成立则继续

原文地址:https://www.cnblogs.com/nxzblogs/p/11144356.html