Link to original problem: 这里写链接内容
Given a collection of distinct 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].
Related problems:
31 Next Permutation: 这里写链接内容
47 Permutations II: 这里写链接内容
60 Permutation Sequence: 这里写链接内容
77 Combinations: 这里写链接内容
英文表达可能有不少问题,所以以后更新还是尽量使用中文QAQ。
本题也是一道非常常规背包问题,这里的排列从1,2,3,…,n。然后是1,2,3,…,n, n-1。依次类推。我们可以讲该问题考虑成一个背包,最终我们是需要讲所有数字都装进这个背包中的,只是装进去的顺序不同而已。
考虑第一次放物体进入背包,我们可以选择从1到n的任意一个数字,并且最先放置1,这个解最终在输出结果的顺序是要先于最先放置2的,而最先放置2的所有解的顺序是要先于所有除1以外的数字的。所以这里我们可以使用一个boolean 数组以标志所有的数字被使用与否,然后在每次的循环中遍历,如果标记为false,则将这个数字装进背包,并进入下一轮背包(recursion)。记得在调用下一轮背包的语句结束之后,拿出这一轮使用的数字即可。下面是具体代码:
public class Solution {
public List<List<Integer>> permute(int[] nums) {
List<List<Integer>> res = new ArrayList<List<Integer>>();
if(nums == null || nums.length == 0) return res;
List<Integer> cur = new ArrayList<Integer>();
boolean[] used = new boolean[nums.length];
helper(res, cur, nums, used, 0);
return res;
}
private void helper(List<List<Integer>> res, List<Integer> cur, int[] nums, boolean[] used, int count){
if(count == nums.length){
res.add(new ArrayList<Integer>(cur));
return;
}
for(int ii = 0; ii < nums.length; ii++){
if(used[ii] == false){
cur.add(nums[ii]);
used[ii] = true;
helper(res, cur, nums, used, count+1);
cur.remove(cur.size()-1);
used[ii] = false;
}
}
}
}