Given a list of numbers, return all possible permutations.
Example
For nums = [1,2,3]
, the permutations are:
[
[1,2,3],
[1,3,2],
[2,1,3],
[2,3,1],
[3,1,2],
[3,2,1]
]
分析:递归。
class Solution {
/**
* @param nums: A list of integers.
* @return: A list of permutations.
*/
public List<List<Integer>> permute(int[] nums) {
List<List<Integer>> res = new ArrayList<List<Integer>>();
helper(nums, res, new ArrayList<Integer>(), new boolean[nums.length]);
return res;
}
void helper(int[] nums, List<List<Integer>> res, List<Integer> list, boolean[] b) {
if(list.size() >= nums.length) {
res.add(new ArrayList<Integer>(list));
return;
}
for(int i = 0; i < nums.length; i++) {
if(!b[i]) {
b[i] = true;
list.add(new Integer(nums[i]));
helper(nums, res, list, b);
list.remove(list.size() - 1);
b[i] = false;
}
}
}
}