Permutations-LeetCode

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

这道题很不幸我没有AC,我的解题思路就是在不同位置间次插入数字,时间复杂度O(N^3)。但是,由于自己设计算法本身的问题,总是出现重复的结果。

import java.util.ArrayList;


public class Permutations {

	public static void main(String args[]){
		ArrayList<ArrayList<Integer>> result = new ArrayList<ArrayList<Integer>>();
		int[] n = {5,4,6,2};
		int size = n.length;
		int time = 0;
		int total = 1;
		int i = 0;
		
		for(i =0; i < size; i++){
			total = total * (i+1);
		}
		for(i = 0 ;i < total;i++)
		{
			ArrayList<Integer> r = new ArrayList<Integer>();
			result.add(r);
		}
		for(i =0; i < size; i++){
			time = total/(i + 1);
			for(int q = 0;q < i+1; q++){
			for(int j = 0; j<time; j++){
				ArrayList<Integer> rr = result.get(q+(i+1)*j);
				rr.add(q,n[i]);
			}	
			}
		}
		System.out.println(result);
	}
}

进而,我查阅了他人 的AC思路,经测试AC。

这类题目面试很常见,应当注意。

Analysis:

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.


public class Solution {
    public ArrayList<ArrayList<Integer>> permute(int[] num) {
        // Start typing your Java solution below
        // DO NOT write main() function
    	
		ArrayList<Integer> cal = new ArrayList<Integer>();//代表一种排列
		ArrayList<ArrayList<Integer>> re = new ArrayList<ArrayList<Integer>>();//总结果
		
		int len = num.length;
		int[] used = new int[len];//记录每一个位置的元素是否被使用过
		
		getpermute(num, used, len, cal, re);
        
		return re;
    }

	public void getpermute(int[] num, int[] used, int len, ArrayList<Integer> cal, ArrayList<ArrayList<Integer>> re){
		if(cal.size() == len){
			ArrayList<Integer> temp = new ArrayList<Integer>(cal);
			re.add(temp);
			return;
		}
		
		for(int i=0; i<len; i++){
			if(used[i] == 0){
				cal.add(num[i]);
				used[i]=1;
				getpermute(num,used,len,cal,re);//思路和我最初设计的一样,使用递归,不知道有没有比递归更简易的方法
				used[i]=0;
				cal.remove(cal.size()-1);//去掉用过的最后的元素,重新从末尾开始permutation
			}
		}
	}
}


  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值