LeetCode进阶之路(Combination Sum)

Given a set of candidate numbers (C) and a target number (T), find all unique combinations in C where the candidate numbers sums to T.

The same repeated number may be chosen from C unlimited number of times.

Note:

  • All numbers (including target) will be positive integers.
  • The solution set must not contain duplicate combinations.

For example, given candidate set [2, 3, 6, 7] and target 7
A solution set is: 

[
  [7],
  [2, 2, 3]
]

题目:给定一个数组和一个目标值target,寻找数组中相加结果等于target的组合,可以重复。这道题目昨天下班前就看了,可是下班了就着急去打球,一点都静不下来思考。思路就是用回溯法,但当时静不下来,思考了半天也没个结果。今天把这道题目补上。

思路:回溯法就是要寻找一个解空间,按照题目的意思,2*n+3*m + 6*x+7*z=7即可,寻找n,m,x,y的组合就行了。

public class Solution {
    List<List<Integer>> list = new ArrayList<List<Integer>>();
	static int len;
	static int target;
	static int[] n;
	static int[] can;
    public List<List<Integer>> combinationSum(int[] candidates, int target) {
		this.len = candidates.length;
		this.n = new int[len];
		this.can = candidates;
		this.target = target;
		Arrays.sort(can);
		helper(0);
		return list;
    }
    
    public void helper(int t) {
		if(t >= len) {
			int sum = 0;
			List<Integer> l = new ArrayList<Integer>();
			for(int i = 0; i < len;i++) {
				for(int j = 0; j < n[i];j++) {
					l.add(can[i]);
					sum = sum + can[i];
				}
			}
			if(sum == target) {
				list.add(l);
			}
			
		} else {
			for(int i = 0; i <= target/can[t];i++) {
				n[t] = i;
				if(isValid(t)) {
					helper(t+1);
				}
			}
		}
	}
	
	public boolean isValid(int t) {
		int sum = 0;
		for(int i = 0; i <= t;i++) {
			for(int j = 0; j < n[i];j++) {
				sum = sum + can[i];
			}
		}
		if(sum > target) {
			return false;
		}
		return true;
	}
}
提交之后看了下时间,相当后面,改进几个for循环,从81ms提高到47ms。百度了一位网友的做法,提交直接12ms,现在贴上他的解法,比我的简洁的多,效率也更高。

public class Solution {  
    List<List<Integer>> ans = new ArrayList<List<Integer>>();  
    int[] cans = {};  
      
    public List<List<Integer>> combinationSum(int[] candidates, int target) {  
        this.cans = candidates;  
        Arrays.sort(cans);  
        backTracking(new ArrayList(), 0, target);  
        return ans;  
    }  
      
    public void backTracking(List<Integer> cur, int from, int target) {  
        if (target == 0) {  
            List<Integer> list = new ArrayList<Integer>(cur);  
            ans.add(list);  
        } else {  
            for (int i = from; i < cans.length && cans[i] <= target; i++) {  
                cur.add(cans[i]);  
                backTracking(cur, i, target - cans[i]);  
                cur.remove(new Integer(cans[i]));  
            }  
        }  
    }  
}  

种一棵树最好的时间是十年前,其次是现在!

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值