回溯算法的基本模板在很多場合有很重要的作用,一般的回溯問題都是在基本的模板上進行變種解決。
回溯算法在排列組合問題上主要分為不可重復回溯和可重復回溯,如:
不可重復回溯:
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 }