【例】
輸入: [1,2,3]
輸出:
[
[1,2,3],
[1,3,2],
[2,1,3],
[2,3,1],
[3,1,2],
[3,2,1]
]
此題運用回溯法 剪枝
Java中實際上提供了java.util.Stack
來實現棧結構,但官方目前已不推薦使用,而是使用java.util.Deque
雙端隊列來實現隊列與棧的各種需求
import java.util.ArrayDeque;
import java.util.ArrayList;
import java.util.Deque;
import java.util.List;
class Solution {
public static List<List<Integer>> permute(int[] nums) {
List<List<Integer>> list =new ArrayList<List<Integer>>();
def(new ArrayDeque<Integer>(), 0, nums.length, nums ,list);
return list;
}
//Deque<Integer> path 存放訪問的路徑節點
// now 當前訪問的節點數,用來結算
//length 訪問的節點總數
static void def(Deque<Integer> path ,int now , int length , int[] nums ,List<List<Integer>> list ) {
//結算路徑
if(now == length) {
list.add(new ArrayList<Integer>(path));
}
for (int i = 0; i < nums.length; i++) {
//如果節點已經被訪問,跳過
if(path.contains(nums[i])) {
continue;
}
//加入節點
path.addLast(nums[i]);
//回溯調用
def(path, now+1, length, nums, list);
//把加入的節點刪除,用於下一次循環進行其他組合的遞歸,
// 若加入節點前的path=[1] 訪問的節點爲2 那麼加入節點後的path[1,2] 爲了不影響路徑 path結果值[1,3],所以應當把path恢復到節點2加入之前的場景 path = [1] 當 訪問節點爲3的時候可以生成path[1,3]
path.removeLast();
}
}
}