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

一遍通过!通过给定的数组返回其所有排列的list。

用的是递归的思想来做的。

1. 对num[]进行排序。题目没有说明给的数组是否是有序的,也没有有求返回的list是否要按照有序顺序返回,但是为了统一,还是先排序吧。

2. 在递归之前先把int[]转为list<integer>。不能用库函数中的Arrays.asList(num)来直接把int[]->list<Integer>。因为Arrays.asList接受的是对象,所以必须是Integer[]之类的。而转成integer[]也只有for循环,那还不如直接list.add来进行。

3. 递归。

递归的退出条件是:list<>只有一个元素。

当list有多个元素的时候,每次拷贝list为tmplist,for循环遍历tmplist,从tmplist中提取出一个元素,加入到把递归结果集中的list的头部即:list.add(0,tmplist.remove(x));

4.返回list<list<Integer>>。

上代码

import java.util.ArrayList;
import java.util.Arrays;
import java.util.Iterator;
import java.util.List;


public class 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].
	 * @param args
	 */
	public List<List<Integer>> getpermute(List<Integer> num) {//递归函数
		List<List<Integer>> resultLists=new ArrayList<>();
		
		if(num.size()==1){//退出条件
			
			resultLists.add(num);
		}
		else{//递归
			
			for(int indexnum=0;indexnum<num.size();++indexnum){
				List<Integer> numtmp=new ArrayList<>(num);//拷贝,
				int first=numtmp.remove(indexnum);
				List<List<Integer>> tmplLists=getpermute(numtmp);
				for (List<Integer> list : tmplLists) {
					list.add(0, first);//添加移出的元素到头部
					resultLists.add(list);
				}
			}
		}
		return resultLists;
		
	}
	public List<List<Integer>> permute(int[] num) {//把num[]转为 List<Integer>
		Arrays.sort(num);
		List<Integer> numlist=new ArrayList<>();
		for(int indexnum=0;indexnum<num.length;++indexnum)numlist.add(num[indexnum]);
		return getpermute(numlist);
        
    }
	public static void main(String[] args) {
		// TODO Auto-generated method stub

	}

}


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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值