Skip to content

Navigation Menu

Sign in
Appearance settings

Search code, repositories, users, issues, pull requests...

Provide feedback

We read every piece of feedback, and take your input very seriously.

Saved searches

Use saved searches to filter your results more quickly

Sign up
Appearance settings

Commit 4c3f57a

Browse files
Create Find the Punishment Number of an Integer
1 parent 1f89dbe commit 4c3f57a

File tree

1 file changed

+29
-0
lines changed

1 file changed

+29
-0
lines changed
Lines changed: 29 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,29 @@
1+
想法:對每個 1 <= i <= n 都測試是否是 punushment number,使用一個遞迴找過所有可能組合;如果任一組合符合條件就輸出 true,否則輸出 false
2+
對每個數字都檢查並把最後答案相加即可
3+
4+
Time Complexity : O(n * 2^(log_10n)) for every number needs O(2^(log_10 n) ) time to check and there are n numbers need to check
5+
Space Complexity : O(2^(log_10n)) for the recursion (recursion depth = O(logn))
6+
7+
class Solution {
8+
public:
9+
bool valid(int num , int target) {
10+
if (target == num )
11+
return true ;
12+
if ( target <= 0 || num == 0 )
13+
return false ;
14+
for(int power = 10 ; power < num ; power *= 10) {
15+
if ( valid(num / power , target - (num % power)) )
16+
return true ;
17+
}
18+
return false ;
19+
}
20+
int punishmentNumber(int n) {
21+
int ans = 0 ;
22+
for(int i = 1 ; i <= n ; i++) {
23+
if ( valid(i * i , i) )
24+
ans += i * i ;
25+
26+
}
27+
return ans ;
28+
}
29+
};

0 commit comments

Comments
(0)

AltStyle によって変換されたページ (->オリジナル) /