leetcode46+77

46. permutations

This question gives an array, we can call it nums and nums has distinct integers, and then it require to return all the possible permutations, which mean you can return the answer in any order. For example, 在这里插入图片描述

Q: how many results in this case?
because nums has three distinct integers, so there will be 321 = 6 results, I mean there will 6 results, right?
Idea:
在这里插入图片描述
code:

public List<List<Integer>> permute(int[] nums) {
		List<List<Integer>> rs = new ArrayList<>();
		int length = nums.length;
		boolean[] used = new boolean[nums.length];
		List<Integer> path = new ArrayList<>();
		dfs(nums,used,rs,path);

		return rs;
    }
	
	public void dfs(int[] nums, boolean[] used, List<List<Integer>> rs,List<Integer> path) {
		/*
		if(depth==nums.length) {
			rs.add(new ArrayList<>(path));
			return;
		}
		*/
		if(path.size()==nums.length) {
			rs.add(new ArrayList<>(path));
			return;
		}
		// 在非叶子结点处,产生不同的分支,
		// 这一操作的语义是:在还未选择的数中依次选择一个元素作为下一个位置的元素,
		// 这显然得通过一个循环实现。
		for(int i=0;i<nums.length;i++) {
			if(!used[i]) {
				path.add(nums[i]);
				used[i]=true;
				System.out.println("  递归之前 => " + path);
				dfs(nums,used,rs,path); // 继续递归填下一个数
				used[i]=false;
				path.remove(path.size()-1); // 先进后出 = 后进先出
				System.out.println("递归之后 => " + path);
			}
			
		}
	}
	
	public static void main(String[] args) {
		System.out.print(new demo46().permute(new int[] {1,2,3}));
		/*
	[[1, 2, 3], [1, 3, 2], [2, 1, 3], [2, 3, 1], [3, 1, 2], [3, 2, 1]]
	*/
	}
	

77. Combinations

Given two integers n and k, return all possible combinations of k numbers out of the range [1, n].
You may return the answer in any order. For example
在这里插入图片描述

Q: how many results in this case?
because we can select 2 distinct integers from range [1,4], so there will be C 4 2 = 6 C_{4}^2=6 C42=6 results, I mean there will 6 results, right?

1 difference:

  • [1,2], [2,1] is the same result

Idea:
在这里插入图片描述

code:

public List<List<Integer>> combine(int n, int k) {
		List<List<Integer>> rs = new ArrayList<>();
		List<Integer> path = new ArrayList<>();
		int start=1;
		dfs(n,k,start,rs,path);
		return rs;
    }
	
	public void dfs(int n, int k,int start,List<List<Integer>> rs,List<Integer> path) {
		/*
		if(depth==k) {
			rs.add(new ArrayList<>(path));
			return;
		}
		*/
		if(path.size()==k) {
			rs.add(new ArrayList<>(path));
			return;
		}
		for(int i=start;i<=n;i++) {
			path.add(i);
			dfs(n,k,i+1,rs,path);
			path.remove(path.size()-1);

		}
	}
	
	public static void main(String[] args) {
		System.out.print(new demo77().combine(4,2));
		/*
	[[1, 2], [1, 3], [1, 4], [2, 3], [2, 4], [3, 4]]
	*/
	}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值