一、题目叙述:
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], [3,2,1] ]
Subscribe to see which companies asked this question.
二、解题思路:
Medium题。几天不刷题,一夜回到解放前,完全参考别人的代码,还老捋不清。
思路:
这道题就用循环递归解决子问题。
因为求所有组合,这就意味着不能重复使用元素,每次检验list中是否已经有了该元素。
因为是所有可能的组合,所以循环length次,就是这里面每位都有可能有length个可能性。
正因为如此,每一层递归就不需要传递一个start点,告诉他从哪开始(因为都是从头开始循环)。
三、源码:
public class Solution {
List<List<Integer>> res = new ArrayList<>();
public List<List<Integer>> permute(int[] nums)
{
if (nums.length == 0) return res;
permutehelp(nums, 0, new ArrayList<Integer>());
return res;
}
private void permutehelp(int[] nums, int start, ArrayList<Integer> list)
{
if (start == nums.length)
{
res.add(new ArrayList<Integer>(list));
return;
}
for (int i = 0; i < nums.length; i++)
{
if(!list.contains(nums[i]))
{
list.add(nums[i]);
permutehelp(nums, start+1, list);
list.remove(list.size() - 1);
}
}
}
}