回溯算法的模板整理

回溯算法的基本模板在很多场合有很重要的作用,一般的回溯问题都是在基本的模板上进行变种解决。

回溯算法在排列组合问题上主要分为不可重复回溯可重复回溯,如:

不可重复回溯:

 1  /**
 2      * 回溯算法不可重复 相当于每一层选择一个进行排列组合
 3      * @param nums
 4      * @param temp
 5      *
 6      * in: 1 2 3
 7      * out: [1]
 8      *      [1, 2]
 9      *      [1, 2, 3]
10      *      [1, 3]
11      *      [2]
12      *      [2, 3]
13      *      [3]
14      *
15      */
16     public void backtrack(int[] nums , int index , Stack<Integer> temp){
17 
18 
19         for(int i  = index; i < nums.length; i++){
20             temp.push(nums[i]);
21             //输出
22             System.out.println(temp);
23             backtrack(nums,i + 1 , temp);
24             temp.pop();
25         }
26     }

可重复回溯:

 1 /**
 2      * 回溯算法重复 相当于每一层都有nums.length 个选择 进行排列组合
 3      * @param nums
 4      * @param temp
 5      *
 6      * in:1 2
 7      * out:[1, 1, 1]
 8      *     [1, 1, 2]
 9      *     [1, 2, 1]
10      *     [1, 2, 2]
11      *     [2, 1, 1]
12      *     [2, 1, 2]
13      *     [2, 2, 1]
14      *     [2, 2, 2]
15      *
16      */
17     public void backtrack_CF(int[] nums , Stack<Integer> temp){
18 
19         if(temp.size() >= 3){
20             System.out.println(temp);
21             return;
22         }
23 
24         for(int i  = 0; i < nums.length; i++){
25             temp.push(nums[i]);
26             backtrack_CF(nums,temp);
27             temp.pop();
28         }
29     }

猜你喜欢

转载自www.cnblogs.com/oldhands/p/11840667.html