Posts Tagged 【dfs】 Combinations
来源:互联网 发布:js splice函数 编辑:程序博客网 时间:2024/06/05 10:53
Combinations
Total Accepted: 38686 Total Submissions: 126278My SubmissionsGiven two integers n and k, return all possible combinations of k numbers out of 1 ... n.
For example,
If n = 4 and k = 2, a solution is:
[ [2,4], [3,4], [2,3], [1,2], [1,3], [1,4],]
/*第一个思路就是dfsn,k(XXX...XXX).size == kevery X = 1.2.3...n 用mark标记是否已经访问Submission Result: Time Limit Exceeded this method's output:combine(4, 2)12=13=14=21=23=24=31=32=34=41=42=43note:[1,2] == [2,1]按照题目的意思应该要标记起始点12=13=14=23=24=34*/public class Solution {public List<List<Integer>> list;public List<Integer> listItem;public boolean[] mark;public int nn;public int kk; public List<List<Integer>> combine(int n, int k) { list = new ArrayList<List<Integer>>(); listItem = new ArrayList<Integer>(); mark = new boolean[n]; kk = k; nn = n; getListItem(0); return list; } private void getListItem(int step) { if(step==kk) { List<Integer> temp = new ArrayList<Integer>(); for(int i = 0;i<listItem.size();i++) temp.add(listItem.get(i)); list.add(temp); return; } for(int i = 0;i<nn;i++) { if(!mark[i]) { mark[i] = true; if(listItem.size() == kk) listItem.set(step, i+1); else { listItem.add(i+1); } getListItem(step+1); mark[i] = false; } } };}
/*对于这种固定长度解法step=0,有何种选择,选择的范围:起点终点,下一步的选择范围是什么直到step=k-1,共进行了k步,当step=k,也就是超出固定长度则处理returnSubmission Result: Accepted*/public class Solution { public List<ArrayList<Integer>> combine(int n, int k) { List<ArrayList<Integer>> list = new ArrayList<ArrayList<Integer>>(); if(k<=0 || n<1) return null; getListItem(1,n,0,list,new int[k]); return list; } private void getListItem(int start, int end, int step, List<ArrayList<Integer>> list, int[] path) { if(step==path.length) { ArrayList<Integer> listItem = new ArrayList<Integer>(); for(int i = 0;i<step;i++) listItem.add(path[i]); list.add(listItem); return; } else { for(int i = start; i<= end;i++) { path[step] = i; getListItem(i+1, end, step+1, list, path); } } };}
update 2015/04/14
0 0
- Posts Tagged 【dfs】 Combinations
- Posts Tagged 【tree && dfs】
- Posts Tagged 【dfs】Generate Parentheses
- Posts Tagged 【dfs】Restore IP Addresses
- Posts Tagged 【dfs】Number of Islands
- Posts Tagged 【Catalan && dfs】Unique Binary Search Trees I && II
- Posts Tagged 【tree && dfs】Sum Root to Leaf Numbers
- Posts Tagged ‘多站’
- Posts Tagged 【String】
- Posts Tagged 【Array】
- Posts Tagged 【Search】
- Posts Tagged 【Math】
- Posts Tagged 【Catalan】
- Posts Tagged 【List】Anagrams
- Posts Tagged 【list && tree && dfs】Flatten Binary Tree to Linked List
- POSTS TAGGED: A/B TEST
- Posts Tagged 【fsm】 Valid Number
- Posts Tagged 【dp】Interleaving String
- UIView和CALayer的区别 说的比较清楚了
- mysql的limit优化
- 函数指针学习2
- 自写字符串连接函数strcat
- python 实现选择排序
- Posts Tagged 【dfs】 Combinations
- /proc/$PID/status
- move_to_user_mode()函数分析
- XSS跨站测试代码大全
- 孤儿进程与僵尸进程
- 一阶逻辑等值演算
- 写给女友的JS教程—之JS闭包
- 怎么访问一个整型数里面的各个字节
- 解决genymotion Qt版本的问题