Given a collection of numbers, return all possible permutations.
For example,[1,2,3]
have the following permutations:
[1,2,3]
, [1,3,2]
, [2,1,3]
, [2,3,1]
, [3,1,2]
,
and [3,2,1]
.
public class Solution {
ArrayList<ArrayList<Integer>> result=new ArrayList<ArrayList<Integer>>();
public ArrayList<ArrayList<Integer>> permute(int[] num) {
if(num.length==0)return null;
myPermute(num,0,new ArrayList<Integer>());
return result;
}
public void myPermute(int[] num,int index,ArrayList<Integer> cur){
for(int i=0;i<=index;i++){
cur.add(i,num[index]);
ArrayList<Integer> a=new ArrayList(cur);
if(index==num.length-1)result.add(a); // we should create a new list because the cur list will
need to be modified later
else if(index<num.length-1)myPermute(num,index+1,cur);
cur.remove(i); //undo effect
}
}
}
這種是backtracking 的典型題目:
思路都是一樣的,在每一步思考在這一步有哪些情況,然後分別嘗試,在每一次嘗試後都要undo 這一步的effect,在符合條件的時候把結果村粗在相應的地方。(我的習慣是在函數中輸入相應的參數傳遞下來)
然後技巧和減小時間複雜度的方法就是有些情況我們是可以排除的,這也是最難的部分。