[LeetCode69]Permutations


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

Analysis:

Recursion, use flag array to identify which one is used.

The idea of this classic problem is to use backtracking.
We want to get permutations, which is mainly about swap values in the list.
Consider:
a --> a
ab --> ab, ba
abc --> abc, acb, bac, bca, cab, cba.
...
where for the length of n, the permutations can be generated by
(1) Swap the 1st element with all the elements, including itself.
(2) Then the 1st element is fixed, go to the next element.
(3) Until the last element is fixed. Output.
It's more clear in the figure above. The key point is to make the big problem into smaller problem, here is how to convert the length n permutation into length n-1 permutation problem.

Java

public class Solution {
    List<List<Integer>> result;
	 ArrayList<Integer> solu;
    public List<List<Integer>> permute(int[] num) {
        result = new ArrayList<>();
		 solu = new ArrayList<>();
		 int[] flag = new int[num.length];
		 for(int i=0;i<flag.length;i++)
			 flag[i]=0;
	    genPermutation(0, num, flag);
		 return result;
    }
    public void genPermutation(int level, int[] num, int[] flag){
		 if(level == num.length){
			 result.add(new ArrayList<>(solu));
			 return;
		 }
		 for(int i=0;i<num.length;i++){
			 if(flag[i]==0){
				 flag[i] = 1;
				 solu.add(num[i]);
				 genPermutation(level+1, num, flag);
				 solu.remove(level);
				 flag[i] = 0;
			 }
		 }
	 }
}
c++

void GeneratePermute(vector<vector<int>> &result,
                     vector<int> &solu,
                     int level,
                     vector<int> &visited,
                     vector<int> &num
                     ){
    if(level == num.size()){
        result.push_back(solu);
        return;
    }
    for(int i=0;i<num.size();i++){
        if(visited[i]==0){
            visited[i]=1;
            solu.push_back(num[i]);
            GeneratePermute(result,solu,level+1,visited,num);
            solu.pop_back();
            visited[i]=0;
        }
    }
}
vector<vector<int> > permute(vector<int> &num) {
    vector<vector<int>> result;
    vector<int> solution;
    vector<int> visited(num.size(),0);
    if(num.size() == 0) return result;
    GeneratePermute(result,solution,0,visited,num);
    return result;
}




你可能感兴趣的:(LeetCode,permutation)