常见算法 - 给定一个数组数字求其的全排列 && 求1~n选k个数的所有组合

给定一个数组数字求其全排列(leetcode46):

Given a collection of distinct integers, return all possible permutations.

Example:

Input: [1,2,3]
Output:
[
  [1,2,3],
  [1,3,2],
  [2,1,3],
  [2,3,1],
  [3,1,2],
  [3,2,1]
]
 

思路:回溯法的练习题。因为我们找到的全排列的长度每个都还是等于数组长度。所以对于每个位置都重数组中找一个未被使用过的(用一个used数组记录是否被使用过),当找到位置等于数组长度了,就是找到了一个排列,即递归的出口。每次递归找下一个位置之后,回溯上一个位置,并将其used置为false。

public class L46Permutations {
	public static void main(String[] args) {
		
		int[] nums = {1,2,3};
		System.out.println(permute(nums));
	}

	static List<List<Integer>>  res = new ArrayList<List<Integer>>();
	static boolean[]  used ;
	public static List<List<Integer>> permute(int[] nums) {
		used = new boolean[nums.length];
        if(nums.length == 0){
        	return null;
        }
        helper(nums,0,new ArrayList<Integer>());
        return res;
	}

	private static void helper(int[] nums, int index, ArrayList<Integer> list) {
		if(index == nums.length){
			System.out.println("index:"+index+"     list:"+list);
			
			res.add(new ArrayList<Integer>(list));
			System.out.println(res);
			return ;
		}	
		
		for(int i = 0 ; i < nums.length; i++){
			if(!used[i]){
				list.add(nums[i]);
				used[i] = true;
				helper(nums,index+1,list);
				list.remove(list.size()-1);
				used[i] = false;
			}
		}
	}
}


求从1~n中选k个数的所有组合(leetcode77):

Given two integers n and k, return all possible combinations of k numbers out of 1 ... n.

Example:

Input: n = 4, k = 2
Output:
[
  [2,4],
  [3,4],
  [2,3],
  [1,2],
  [1,3],
  [1,4],
]

思路:与上题思路类似,不过每次选完当前的数,递归调用下一个位置就只能从当前数+1开始选了,因为是求组合,不能重复选择。
class Solution {

    List<List<Integer>> res = new ArrayList<List<Integer>>();
	
    public List<List<Integer>> combine(int n, int k) {
    	helper(n,k,1,0,new ArrayList<Integer>());
    	return res;
    }
    
    public void helper(int n, int k, int start,int index,ArrayList<Integer> list){
    	if(index == k){
    		res.add(new ArrayList<Integer>(list));
    		return;
    	}
    	
    	for(int i = start; i <= n; i++){
    		list.add(i);
    		helper(n,k,i+1,index+1,list);
    		list.remove(list.size()-1);
    	}
    }
}

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值