Integer Break
2016-04-27 11:50
274 查看
最近,相对比较闲,开始刷leetcode,觉得花点时间记录一下自己的刷题历程也未尝不可。
/*******************************************************************************************************************************************/
Integer Break这个题,感觉最重要的还是要有一个好的数学知识,一开始也不知道一个数该怎么分才能够满足要求,经过几次失败后,发现,写成3的幂的形式可能是最好的,于是开始尝试;对于n=2,n=3,n=4是比较特别的,可以不放入其中;当n>=5时,我们就把这些n归为3类:
第一类:能整除3,那么可以return pow(3,n/3);
第二类:除3余1,那么这个数可以分成4+3+3+...+3((n-4)/3个3加上4),因此返回4*pow(3,(n-4)/3);
第三类:除3余2,那么这个数可以分成2+3+3+...+3((n-2)/3个3加上2),,因此返回2*pow(3,(n-2)/3);
/***************************************************************************************************************************************/
好啦,把代码也放上来,便于以后有新想法进行对比。
class Solution {
public:
int integerBreak(int n) {
if(n==2) return 1;
if(n==3) return 2;
if(n==4) return 4;
int m=n%3;
switch(m)
{
case 0:return pow(3,n/3);
case 1:return 4*pow(3,(n-4)/3);
default:return 2*pow(3,(n-2)/3);
}
}
};
/*******************************************************************************************************************************************/
Integer Break这个题,感觉最重要的还是要有一个好的数学知识,一开始也不知道一个数该怎么分才能够满足要求,经过几次失败后,发现,写成3的幂的形式可能是最好的,于是开始尝试;对于n=2,n=3,n=4是比较特别的,可以不放入其中;当n>=5时,我们就把这些n归为3类:
第一类:能整除3,那么可以return pow(3,n/3);
第二类:除3余1,那么这个数可以分成4+3+3+...+3((n-4)/3个3加上4),因此返回4*pow(3,(n-4)/3);
第三类:除3余2,那么这个数可以分成2+3+3+...+3((n-2)/3个3加上2),,因此返回2*pow(3,(n-2)/3);
/***************************************************************************************************************************************/
好啦,把代码也放上来,便于以后有新想法进行对比。
class Solution {
public:
int integerBreak(int n) {
if(n==2) return 1;
if(n==3) return 2;
if(n==4) return 4;
int m=n%3;
switch(m)
{
case 0:return pow(3,n/3);
case 1:return 4*pow(3,(n-4)/3);
default:return 2*pow(3,(n-2)/3);
}
}
};
相关文章推荐
- leetcode 179 Largest Number
- leetcode 24 Swap Nodes in Pairs
- leetcode 2 Add Two Numbers 方法1
- leetcode 2 Add Two Numbers 方法2
- leetcode----Longest Substring Without Repeating Characters
- [LeetCode]47 Permutations II
- [LeetCode]65 Valid Number
- [LeetCode]123 Best Time to Buy and Sell Stock III
- [LeetCode] String Reorder Distance Apart
- [LeetCode] Sliding Window Maximum
- [LeetCode] Find the k-th Smallest Element in the Union of Two Sorted Arrays
- [LeetCode] Determine If Two Rectangles Overlap
- [LeetCode] A Distance Maximizing Problem
- leetcode_linearList
- leetcode_linearList02
- 021-Merge Two Sorted Lists(合并两个排好序的单链表);leetcode
- LeetCode[Day 1] Two Sum 题解
- LeetCode[Day 2] Median of Two Sorted Arrays 题解
- LeetCode[Day 3] Longest Substring Without... 题解
- LeetCode [Day 4] Add Two Numbers 题解