LeetCode:Permutations

来源:互联网 发布:达内科技 php培训 编辑:程序博客网 时间:2024/06/05 13:28

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].

是道搜索题,这种类型的题目在LeetCode有几道。

package leetcode;import java.util.ArrayList;import java.util.Arrays;public class Permutations {public ArrayList<ArrayList<Integer>> permute(int[] num) {ArrayList<ArrayList<Integer>> result = new ArrayList<ArrayList<Integer>>();if (num == null || num.length == 0) {return result;}boolean[] flag = new boolean[num.length];Arrays.fill(flag, false);int[] pos = new int[num.length];Arrays.fill(pos, -1);int index = 0;while (index >= 0) {int oldP = pos[index];pos[index]++;while (pos[index] < num.length && flag[pos[index]]) {pos[index]++;}int p = pos[index];if (p == num.length) {//backif (oldP != -1) {flag[oldP] = false;}if (index - 1 >= 0) {flag[pos[index - 1]] = false;}index--;} else {if (!flag[p]) {flag[p] = true;if (index == num.length - 1) {ArrayList<Integer> r = new ArrayList<Integer>(num.length);for (int pp : pos) {r.add(num[pp]);}result.add(r);//find a new resultflag[p] = false;} else {index++;pos[index] = -1;}}}}return result;}}