[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;
}




评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值