LeetCode46.給定一個沒有重復(fù)數(shù)字的序列,返回其所有可能的全排列。例如:
輸入:[1,2,3]
輸出:[[1,2,3],[1,3,2],[2,1,3],[2,3,1],[3,1,2],[3,2,1]]
元素1在[1,2]中已經(jīng)使用過了,但是在[2,1]中還要再使用一次,所以就不能使用startlndex了,為此可以使用一個used數(shù)組來標(biāo)記已經(jīng)選擇的元素文章來源:http://www.zghlxwxcb.cn/news/detail-698774.html
class Permute {
List<List<Integer>> res = new ArrayList<>();
LinkedList<Integer> path = new LinkedList<>();
boolean[] used;
public List<List<Integer>> permute(int[] nums) {
if (nums.length == 0) {
return res;
}
used = new boolean[nums.length];
permuteHelper(nums);
return res;
}
private void permuteHelper(int[] nums) {
if (path.size() == nums.length) {
res.add(new ArrayList<>(path));
return;
}
for (int i = 0; i < nums.length; i++) {
if (used[i]) {
continue;
}
used[i] = true;
path.add(nums[i]);
permuteHelper(nums);
path.removeLast();
used[i] = false;
}
}
}
在這里for循環(huán)中,used[i]的變化可以這樣理解,現(xiàn)在這一層剛上來當(dāng)前元素肯定是沒有使用過的,在執(zhí)行了將used數(shù)組當(dāng)前元素變?yōu)橐咽褂?,將?dāng)前元素添加到path中后,就要進(jìn)入他的下一層了,在他的下面幾層當(dāng)前元素都是使用過的。文章來源地址http://www.zghlxwxcb.cn/news/detail-698774.html
到了這里,關(guān)于算法通關(guān)村第十八關(guān)——排列問題的文章就介紹完了。如果您還想了解更多內(nèi)容,請在右上角搜索TOY模板網(wǎng)以前的文章或繼續(xù)瀏覽下面的相關(guān)文章,希望大家以后多多支持TOY模板網(wǎng)!