ITeye博客

[leetcode]Combination sum

ouqi · 2013-09-15 15:42 · 找工作系列之-刷题记录 · 编程语言 · Markdown

典型的DFS吧 这一类还有permutation啊,求组合啊,之类的~~~

代码:

public class Solution {
    private ArrayList<ArrayList<Integer>> result = new ArrayList<ArrayList<Integer>>();
    public ArrayList<ArrayList<Integer>> combinationSum(int[] candidates, int target) {
        // Start typing your Java solution below
        // DO NOT write main() function
        if(candidates == null||candidates.length == 0) return null;
        int len = candidates.length;
        Arrays.sort(candidates);
        result.clear();
        ArrayList<Integer> list = new ArrayList<Integer>();
        
        dfs(candidates,target,list,0);
        return result;
        
    }
    
    public void dfs(int[]a,int key, ArrayList<Integer> list,int i){
        if(key == 0){//找到解
            ArrayList<Integer> temp = new ArrayList<Integer>();
            temp.addAll(list);
            result.add(temp);
            return;
        }
        if(i == a.length) return;
        dfs(a,key,list,i+1);//不选择a[i];
        int count = 1;
        while(a[i]*count <= key){//重复选择a[i]
            for(int j = 1;j<=count;j++)
               list.add(a[i]);
            dfs(a,key-a[i]*count,list,i+1);
            for(int j = 1;j<=count;j++)
                list.remove(list.size()-1);
            count++;
        }
    }
}

 Combination Sum II

//待补充~

评论(0)

暂无评论。

评论功能维护中,当前仅展示历史评论。