中级农民
- 积分
- 155
- 大米
- 颗
- 鳄梨
- 个
- 水井
- 尺
- 蓝莓
- 颗
- 萝卜
- 根
- 小米
- 粒
- 学分
- 个
- 注册时间
- 2014-4-17
- 最后登录
- 1970-1-1
|
写了下第二题,请问面试官是要优化空间还是时间呢?
- public class PerfectSquaresII {
-
- public static void main(String[] args) {
- List<Integer> res = getPerfectSquaresII(14);
- for (int i : res) {
- System.out.print(i + " ");
- }
- System.out.println();
- List<Integer> res1 = getPerfectSquaresII(50);
- for (int i : res1) {
- System.out.print(i + " ");
- }
- }
- public static List<Integer> getPerfectSquaresII(int n) {
- int[] dp = new int[n + 2];
- dp[0] = 0;
- HashMap<Integer, List<Integer>> map = new HashMap<Integer, List<Integer>>();
- map.put(0, new ArrayList<Integer>());
- for (int i = 1; i <= n; i++) {
- dp[i] = i;
- for (int j = 1; j * j <= i; j++) {
- if (1 + dp[i - j * j] < dp[i]) {
- dp[i] = 1 + dp[i - j * j] ;
- map.put(i, new ArrayList<Integer>(map.get(i - j * j)));
- map.get(i).add(j * j);
- }
- }
- }
-
- Collections.sort(map.get(n), Collections.reverseOrder());
- return map.get(n);
- }
-
- }
复制代码 |
|